"""FastAPI router for Codex AI agent endpoints."""
from __future__ import annotations

import logging
from typing import Optional

from fastapi import APIRouter, HTTPException

from mesh.codex.models import (
    CodexAgentInfo, CodexTask, CodexTaskResult, CodexTaskSubmission,
)
from mesh.models import StatusResponse

logger = logging.getLogger(__name__)

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

# Wired by start_controller.py
_orchestrator = None


def wire_codex(orchestrator):
    """Wire in the Codex orchestrator."""
    global _orchestrator
    _orchestrator = orchestrator


# ── Agent Endpoints ──────────────────────────────────────────────────────────

@router.get("/agents")
async def list_agents() -> list[CodexAgentInfo]:
    """List all Codex agents and their status."""
    if _orchestrator is None:
        raise HTTPException(503, "Codex orchestrator not ready")
    return _orchestrator.get_all_agents()


@router.post("/agents/{agent_type}/run")
async def run_agent(agent_type: str, target: str = "",
                    parameters: Optional[dict] = None) -> CodexTaskResult:
    """Trigger an agent manually and wait for the result."""
    if _orchestrator is None:
        raise HTTPException(503, "Codex orchestrator not ready")

    agent = _orchestrator.get_agent(agent_type)
    if agent is None:
        raise HTTPException(404, f"Agent type '{agent_type}' not found")

    result = await _orchestrator.run_agent(
        agent_type=agent_type,
        target=target,
        parameters=parameters or {},
    )
    return result


# ── Task Endpoints ───────────────────────────────────────────────────────────

@router.post("/tasks")
async def submit_task(submission: CodexTaskSubmission) -> CodexTask:
    """Submit a task to the Codex queue."""
    if _orchestrator is None:
        raise HTTPException(503, "Codex orchestrator not ready")
    task = await _orchestrator.submit_task(submission)
    return task


@router.get("/tasks")
async def list_tasks(task_type: Optional[str] = None,
                     limit: int = 50) -> list[dict]:
    """List tasks with optional filters."""
    if _orchestrator is None:
        return []
    return _orchestrator.get_results(limit=limit, task_type=task_type)


@router.get("/tasks/{task_id}")
async def get_task(task_id: str) -> dict:
    """Get task details and results."""
    if _orchestrator is None:
        raise HTTPException(503, "Codex orchestrator not ready")
    tasks = _orchestrator.get_results(limit=1000)
    for t in tasks:
        if t.get("task_id") == task_id:
            return t
    raise HTTPException(404, f"Task {task_id} not found")


# ── Findings Endpoint ────────────────────────────────────────────────────────

@router.get("/findings")
async def get_findings(severity: Optional[str] = None,
                       limit: int = 100) -> list[dict]:
    """Get aggregated findings across all tasks."""
    if _orchestrator is None:
        return []
    return _orchestrator.get_findings(limit=limit, severity=severity)
