"""Action run routes.

Moved from app.admin_dashboard in v4.7.2. The handlers still reuse
legacy helpers to keep this refactor behavior-preserving.
"""
from fastapi import APIRouter
import app.admin_dashboard as legacy
from app.admin_dashboard import *  # noqa: F401,F403

router = APIRouter()


@router.get("/runs", response_class=HTMLResponse)
async def runs_page(limit: int = 100):
    runs = list_action_runs(limit=limit)

    rows = ""
    for run in runs:
        decision = run.get("action_decision") or {}
        result = run.get("action_result") or {}

        rows += f"""
        <tr>
            <td>{esc(run["created_at"])}</td>
            <td>#{esc(run.get("conversation_id"))}</td>
            <td>{esc(run.get("decision_source"))}</td>
            <td>{esc(decision.get("action_code"))}</td>
            <td>{esc(result.get("route"))}</td>
            <td>{esc(run.get("provider"))}</td>
            <td>{esc(run.get("total_tokens"))}</td>
            <td>{esc(run.get("cost"))}</td>
            <td>{status_badge("failed" if run.get("needs_review") else "sent")}</td>
        </tr>
        """

    body = f"""
    <table>
        <thead>
            <tr>
                <th>Criado</th>
                <th>Conversa</th>
                <th>Fonte</th>
                <th>Ação</th>
                <th>Rota</th>
                <th>Provider</th>
                <th>Tokens</th>
                <th>Custo</th>
                <th>Review</th>
            </tr>
        </thead>
        <tbody>{rows}</tbody>
    </table>
    """

    return layout("Action Runs", "Histórico de decisões do Action Core.", body, "runs")


