"""Agent scorecard routes — API endpoints for generating and viewing scorecards."""

from __future__ import annotations

import logging
from datetime import datetime

from fastapi import APIRouter, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse

from dashboard.services.scorecard_service import (
    PeriodType,
    generate_all_scorecards,
    generate_scorecard,
    get_tracked_agents,
)
from dashboard.templating import templates

logger = logging.getLogger(__name__)

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


def _format_period_label(period_type: PeriodType) -> str:
    """Format a period type for display."""
    return "Daily" if period_type == PeriodType.daily else "Weekly"


@router.get("/api/agents")
async def list_tracked_agents() -> dict[str, list[str]]:
    """Return the list of tracked agent IDs.

    Returns:
        Dict with "agents" key containing list of agent IDs
    """
    return {"agents": get_tracked_agents()}


@router.get("/api/{agent_id}")
async def get_agent_scorecard(
    agent_id: str,
    period: str = Query(default="daily", description="Period type: 'daily' or 'weekly'"),
) -> JSONResponse:
    """Generate a scorecard for a specific agent.

    Args:
        agent_id: The agent ID (e.g., 'kimi', 'claude')
        period: 'daily' or 'weekly' (default: daily)

    Returns:
        JSON response with scorecard data
    """
    try:
        period_type = PeriodType(period.lower())
    except ValueError:
        return JSONResponse(
            status_code=400,
            content={"error": f"Invalid period '{period}'. Use 'daily' or 'weekly'."},
        )

    try:
        scorecard = generate_scorecard(agent_id, period_type)

        if scorecard is None:
            return JSONResponse(
                status_code=404,
                content={"error": f"No scorecard found for agent '{agent_id}'"},
            )

        return JSONResponse(content=scorecard.to_dict())

    except Exception as exc:
        logger.error("Failed to generate scorecard for %s: %s", agent_id, exc)
        return JSONResponse(
            status_code=500,
            content={"error": f"Failed to generate scorecard: {str(exc)}"},
        )


@router.get("/api")
async def get_all_scorecards(
    period: str = Query(default="daily", description="Period type: 'daily' or 'weekly'"),
) -> JSONResponse:
    """Generate scorecards for all tracked agents.

    Args:
        period: 'daily' or 'weekly' (default: daily)

    Returns:
        JSON response with list of scorecard data
    """
    try:
        period_type = PeriodType(period.lower())
    except ValueError:
        return JSONResponse(
            status_code=400,
            content={"error": f"Invalid period '{period}'. Use 'daily' or 'weekly'."},
        )

    try:
        scorecards = generate_all_scorecards(period_type)
        return JSONResponse(
            content={
                "period": period_type.value,
                "scorecards": [s.to_dict() for s in scorecards],
                "count": len(scorecards),
            }
        )

    except Exception as exc:
        logger.error("Failed to generate scorecards: %s", exc)
        return JSONResponse(
            status_code=500,
            content={"error": f"Failed to generate scorecards: {str(exc)}"},
        )


@router.get("", response_class=HTMLResponse)
async def scorecards_page(request: Request) -> HTMLResponse:
    """Render the scorecards dashboard page.

    Returns:
        HTML page with scorecard interface
    """
    agents = get_tracked_agents()
    return templates.TemplateResponse(
        request,
        "scorecards.html",
        {
            "agents": agents,
            "periods": ["daily", "weekly"],
        },
    )


@router.get("/panel/{agent_id}", response_class=HTMLResponse)
async def agent_scorecard_panel(
    request: Request,
    agent_id: str,
    period: str = Query(default="daily"),
) -> HTMLResponse:
    """Render an individual agent scorecard panel (for HTMX).

    Args:
        request: The request object
        agent_id: The agent ID
        period: 'daily' or 'weekly'

    Returns:
        HTML panel with scorecard content
    """
    try:
        period_type = PeriodType(period.lower())
    except ValueError:
        period_type = PeriodType.daily

    try:
        scorecard = generate_scorecard(agent_id, period_type)

        if scorecard is None:
            return HTMLResponse(
                content=f"""
                <div class="card mc-panel">
                    <h5 class="card-title">{agent_id.title()}</h5>
                    <p class="text-muted">No activity recorded for this period.</p>
                </div>
                """,
                status_code=200,
            )

        data = scorecard.to_dict()

        # Build patterns HTML
        patterns_html = ""
        if data["patterns"]:
            patterns_list = "".join([f"<li>{p}</li>" for p in data["patterns"]])
            patterns_html = f"""
            <div class="mt-3">
                <h6>Patterns</h6>
                <ul class="list-unstyled text-info">
                    {patterns_list}
                </ul>
            </div>
            """

        # Build bullets HTML
        bullets_html = "".join([f"<li>{b}</li>" for b in data["narrative_bullets"]])

        # Build metrics summary
        metrics = data["metrics"]

        html_content = f"""
        <div class="card mc-panel">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">{agent_id.title()}</h5>
                <span class="badge bg-secondary">{_format_period_label(period_type)}</span>
            </div>
            <div class="card-body">
                <ul class="list-unstyled mb-3">
                    {bullets_html}
                </ul>
                
                <div class="row text-center small">
                    <div class="col">
                        <div class="text-muted">PRs</div>
                        <div class="fw-bold">{metrics["prs_opened"]}/{metrics["prs_merged"]}</div>
                        <div class="text-muted" style="font-size: 0.75rem;">
                            {int(metrics["pr_merge_rate"] * 100)}% merged
                        </div>
                    </div>
                    <div class="col">
                        <div class="text-muted">Issues</div>
                        <div class="fw-bold">{metrics["issues_touched"]}</div>
                    </div>
                    <div class="col">
                        <div class="text-muted">Tests</div>
                        <div class="fw-bold">{metrics["tests_affected"]}</div>
                    </div>
                    <div class="col">
                        <div class="text-muted">Tokens</div>
                        <div class="fw-bold {"text-success" if metrics["token_net"] >= 0 else "text-danger"}">
                            {"+" if metrics["token_net"] > 0 else ""}{metrics["token_net"]}
                        </div>
                    </div>
                </div>
                
                {patterns_html}
            </div>
        </div>
        """

        return HTMLResponse(content=html_content)

    except Exception as exc:
        logger.error("Failed to render scorecard panel for %s: %s", agent_id, exc)
        return HTMLResponse(
            content=f"""
            <div class="card mc-panel border-danger">
                <h5 class="card-title">{agent_id.title()}</h5>
                <p class="text-danger">Error loading scorecard: {str(exc)}</p>
            </div>
            """,
            status_code=200,
        )


@router.get("/all/panels", response_class=HTMLResponse)
async def all_scorecard_panels(
    request: Request,
    period: str = Query(default="daily"),
) -> HTMLResponse:
    """Render all agent scorecard panels (for HTMX).

    Args:
        request: The request object
        period: 'daily' or 'weekly'

    Returns:
        HTML with all scorecard panels
    """
    try:
        period_type = PeriodType(period.lower())
    except ValueError:
        period_type = PeriodType.daily

    try:
        scorecards = generate_all_scorecards(period_type)

        panels: list[str] = []
        for scorecard in scorecards:
            data = scorecard.to_dict()

            # Build patterns HTML
            patterns_html = ""
            if data["patterns"]:
                patterns_list = "".join([f"<li>{p}</li>" for p in data["patterns"]])
                patterns_html = f"""
                <div class="mt-3">
                    <h6>Patterns</h6>
                    <ul class="list-unstyled text-info">
                        {patterns_list}
                    </ul>
                </div>
                """

            # Build bullets HTML
            bullets_html = "".join([f"<li>{b}</li>" for b in data["narrative_bullets"]])
            metrics = data["metrics"]

            panel_html = f"""
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card mc-panel">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">{scorecard.agent_id.title()}</h5>
                        <span class="badge bg-secondary">{_format_period_label(period_type)}</span>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled mb-3">
                            {bullets_html}
                        </ul>
                        
                        <div class="row text-center small">
                            <div class="col">
                                <div class="text-muted">PRs</div>
                                <div class="fw-bold">{metrics["prs_opened"]}/{metrics["prs_merged"]}</div>
                                <div class="text-muted" style="font-size: 0.75rem;">
                                    {int(metrics["pr_merge_rate"] * 100)}% merged
                                </div>
                            </div>
                            <div class="col">
                                <div class="text-muted">Issues</div>
                                <div class="fw-bold">{metrics["issues_touched"]}</div>
                            </div>
                            <div class="col">
                                <div class="text-muted">Tests</div>
                                <div class="fw-bold">{metrics["tests_affected"]}</div>
                            </div>
                            <div class="col">
                                <div class="text-muted">Tokens</div>
                                <div class="fw-bold {"text-success" if metrics["token_net"] >= 0 else "text-danger"}">
                                    {"+" if metrics["token_net"] > 0 else ""}{metrics["token_net"]}
                                </div>
                            </div>
                        </div>
                        
                        {patterns_html}
                    </div>
                </div>
            </div>
            """
            panels.append(panel_html)

        html_content = f"""
        <div class="row">
            {"".join(panels)}
        </div>
        <div class="text-muted small mt-2">
            Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC")}
        </div>
        """

        return HTMLResponse(content=html_content)

    except Exception as exc:
        logger.error("Failed to render all scorecard panels: %s", exc)
        return HTMLResponse(
            content=f"""
            <div class="alert alert-danger">
                Error loading scorecards: {str(exc)}
            </div>
            """,
            status_code=200,
        )
