from fastapi import APIRouter, HTTPException
from pathlib import Path

router = APIRouter(prefix="/api/planfile", tags=["planfile"])


@router.get("/status/{project_name}")
async def get_strategy_status(project_name: str):
    """Get execution status of imported strategy for a project."""
    from proxym.planfile.tracker import get_strategy_progress
    
    try:
        status = get_strategy_progress(project_name)
        return status
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/gates/{project_name}")
async def get_quality_gates(project_name: str, strategy_path: str = "strategy.yaml"):
    """Check quality gates for a project's strategy."""
    from proxym.planfile.tracker import check_quality_gates
    
    # Try to find strategy.yaml in the project directory
    project_path = Path(strategy_path)
    if not project_path.is_absolute():
        # If relative, assume it's in the project directory
        from proxym.dashboard._projects_api import _projects
        projects = _projects()
        proj = projects.get_project_by_name(project_name)
        if proj:
            project_path = Path(proj.local_path) / strategy_path
        else:
            project_path = Path(strategy_path)
    
    if not project_path.exists():
        raise HTTPException(status_code=404, detail=f"Strategy file not found: {strategy_path}")
    
    try:
        results = check_quality_gates(str(project_path), str(project_path.parent))
        return {"quality_gates": results}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/import/{project_name}")
async def import_strategy(project_name: str, strategy_path: str, dry_run: bool = False):
    """Import a strategy file as tickets for a project."""
    from proxym.planfile.importer import import_strategy
    
    # Validate strategy path exists
    if not Path(strategy_path).exists():
        raise HTTPException(status_code=404, detail=f"Strategy file not found: {strategy_path}")
    
    try:
        result = import_strategy(strategy_path, project_name, dry_run=dry_run)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/update/{ticket_id}")
async def update_ticket_from_planfile(
    ticket_id: str,
    status: str,
    model_used: str | None = None,
    validation_score: float | None = None,
    files_changed: list[str] | None = None,
    error: str | None = None,
):
    """Update a ticket status from planfile execution."""
    from proxym.planfile.tracker import update_task_status
    
    try:
        update_task_status(
            ticket_id=ticket_id,
            status=status,
            model_used=model_used,
            validation_score=validation_score,
            files_changed=files_changed,
            error=error,
        )
        return {"success": True, "ticket_id": ticket_id}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
