"""Query results retrieval and CSV download endpoints."""

from __future__ import annotations

from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import FileResponse

from conversations.conversation_manager import ConversationManager
from conversations.result_storage import ResultStorage
from database.local_pg import LocalPG

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


@router.get("/{message_id}")
async def get_results(request: Request, message_id: str):
    """Get query results for a specific message."""
    settings = request.app.state.settings
    db = request.app.state.db
    local_pg = LocalPG(db)
    storage = ResultStorage(settings, db, local_pg)

    results = await storage.get_results(message_id)
    if not results:
        raise HTTPException(404, "Results not found")
    return results


@router.get("/{message_id}/csv")
async def download_csv(request: Request, message_id: str):
    """Download results as CSV file."""
    settings = request.app.state.settings
    db = request.app.state.db
    local_pg = LocalPG(db)
    storage = ResultStorage(settings, db, local_pg)

    csv_path = storage.get_csv_path(message_id)
    if not csv_path:
        raise HTTPException(404, "CSV file not found")

    return FileResponse(
        path=str(csv_path),
        media_type="text/csv",
        filename=f"results_{message_id}.csv",
    )


@router.get("/{message_id}/metadata")
async def get_result_metadata(request: Request, message_id: str):
    """Get message metadata without full result data."""
    cm = ConversationManager(request.app.state.db)
    message = await cm.get_message(message_id)
    if not message:
        raise HTTPException(404, "Message not found")
    return {
        "id": message["id"],
        "sql_query": message.get("sql_query"),
        "has_results": message.get("has_results"),
        "row_count": message.get("row_count"),
        "chart_config": message.get("chart_config"),
        "execution_time_ms": message.get("execution_time_ms"),
    }
