"""Reports API router (P4-M4).

Generate and download simulation reports.
"""
import os
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import Any, Dict, Optional

from ..services.report_generator import get_report_generator

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


class GenerateReportRequest(BaseModel):
    task_data: Dict[str, Any]
    ai_analysis: Optional[Dict[str, Any]] = None
    report_title: Optional[str] = None


@router.post("/generate")
async def generate_report(req: GenerateReportRequest) -> Dict[str, Any]:
    """Generate a simulation report."""
    generator = get_report_generator()
    filepath = generator.generate_report(
        task_data=req.task_data,
        ai_analysis=req.ai_analysis,
        report_title=req.report_title,
    )
    filename = os.path.basename(filepath)
    return {"success": True, "filename": filename, "path": filepath}


@router.get("/list")
async def list_reports() -> Dict[str, Any]:
    """List all generated reports."""
    generator = get_report_generator()
    reports = generator.list_reports()
    return {"reports": reports, "count": len(reports)}


@router.get("/download/{filename}")
async def download_report(filename: str):
    """Download a report file."""
    generator = get_report_generator()
    filepath = os.path.join(generator.output_dir, filename)
    if not os.path.exists(filepath):
        raise HTTPException(status_code=404, detail=f"Report {filename} not found")
    return FileResponse(filepath, filename=filename)
