import os
import sys
import uvicorn
import typer
from typing import Optional
from pathlib import Path
from ombra.logger import logger

app = typer.Typer(name="ombra", help="Ombra Workflow Orchestration CLI")

def _get_project_root() -> Path:
    """Find the project root (where pyproject.toml or workflows/ exists)."""
    # Simple heuristic: current directory
    return Path.cwd()

@app.command()
def dev(
    port: int = typer.Option(8000, help="Port to run the server on"),
    host: str = typer.Option("127.0.0.1", help="Host to bind the server to"),
    reload: bool = typer.Option(True, help="Enable auto-reload"),
    workflows_dir: Optional[str] = typer.Option(None, help="Directory containing workflows")
):
    """
    Start the Ombra development server with hot-reloading.
    Automatically discovers workflows in 'workflows/' or 'src/workflows/'.
    """
    project_root = _get_project_root()
    
    # Add project root to sys.path so imports work
    if str(project_root) not in sys.path:
        sys.path.insert(0, str(project_root))
    
    # Set environment variable for discovery logic to find the user's code
    if workflows_dir:
        os.environ["OMBRA_WORKFLOWS_DIR"] = workflows_dir
    

    # We run the 'create_app' factory from ombra.web.app
    # Uvicorn needs a string "module:attribute" for reload to work
    uvicorn.run(
        "ombra.web.app:app",
        host=host,
        port=port,
        reload=reload,
        # We watch the current directory for changes
        reload_dirs=[str(project_root)],
        log_level="info"
    )

@app.command()
def serve(
    port: int = typer.Option(8000, help="Port to run the server on"),
    host: str = typer.Option("0.0.0.0", help="Host to bind the server to"),
    workers: int = typer.Option(1, help="Number of worker processes")
):
    """
    Start the Ombra production server.
    """
    
    uvicorn.run(
        "ombra.web.app:app",
        host=host,
        port=port,
        workers=workers,
        log_level="info"
    )

if __name__ == "__main__":
    app()
