import sys
import os
import subprocess
from app import create_app, db
from app.models import Folder, User
from flask.cli import with_appcontext
import click

app = create_app()


@app.cli.command("setup-dev")
def setup_dev():
    """Set up development environment with Docker Compose."""
    # Create tmp directory for IMAP data if it doesn't exist
    os.makedirs('tmp/imap-data', exist_ok=True)
    
    # Start the services
    try:
        subprocess.run(['docker-compose', 'up', '-d'], check=True)
        print("Services started successfully:")
        print("- PostgreSQL: localhost:5432 (database: email_organizer_dev, user: postgres, password: password)")
        print("- IMAP Server: localhost:1143")
        print("  Users:")
        print("    - user1@example.com / password1")
        print("    - user2@example.com / password2")
        print("  Folders: INBOX, Pending, Work, Personal, Receipts, Marketing, Archived")
    except subprocess.CalledProcessError as e:
        print(f"Error starting services: {e}")
        sys.exit(1)
    except FileNotFoundError:
        print("Docker Compose not found. Please install Docker and Docker Compose.")
        sys.exit(1)

@app.cli.command("start-scheduler")
@click.option('--interval', default=5, help='Interval in minutes between processing runs (default: 5)')
@with_appcontext
def start_scheduler(interval):
    """Start the background email processing scheduler."""
    if not hasattr(app, 'scheduler'):
        print("Scheduler not available. Make sure app/scheduler.py exists and is properly imported.")
        sys.exit(1)
    
    print(f"Starting email processing scheduler with {interval} minute interval...")
    print("Press Ctrl+C to stop")
    
    try:
        # Start the scheduler
        app.scheduler.start()
        
        # Keep the main thread alive
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\nShutting down scheduler...")
            app.scheduler.stop()
            
    except Exception as e:
        print(f"Error starting scheduler: {e}")
        sys.exit(1)

# Import at the top of the file (add this import if not already present)
import time