from __future__ import annotations

from html import escape

from agentkit_cli import __version__
from agentkit_cli.burn import BurnReport


def render_burn_html(report: BurnReport) -> str:
    top_projects = report.totals.get("by_project", [])
    findings = report.findings
    sessions = report.top_sessions
    project_rows = "".join(
        f"<tr><td>{escape(str(row['key']))}</td><td>{row['cost_usd']:.6f}</td><td>{row['turns']}</td><td>{row['tool_calls']}</td></tr>"
        for row in top_projects
    )
    finding_rows = "".join(
        f"<li><strong>{escape(finding.title)}</strong> <span class='sev {escape(finding.severity)}'>{escape(finding.severity)}</span><br><code>{escape(str(finding.evidence))}</code></li>"
        for finding in findings
    ) or "<li>No waste patterns detected.</li>"
    session_rows = "".join(
        f"<tr><td>{escape(session['session_id'])}</td><td>{escape(str(session['project_root'] or 'unknown'))}</td><td>{session['cost_usd']:.6f}</td><td>{session['turns']}</td><td>{session['tool_calls']}</td></tr>"
        for session in sessions
    )
    return f"""<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>agentkit burn report</title>
<style>
body {{ background:#0d1117; color:#e6edf3; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; padding:24px; }}
.card {{ max-width:1100px; margin:0 auto; background:#161b22; border:1px solid #30363d; border-radius:12px; padding:24px; }}
h1,h2 {{ color:#58a6ff; }}
.grid {{ display:grid; grid-template-columns:repeat(4,1fr); gap:12px; margin:20px 0; }}
.metric {{ background:#0d1117; border:1px solid #30363d; border-radius:8px; padding:14px; }}
.metric .value {{ font-size:1.5rem; font-weight:700; }}
table {{ width:100%; border-collapse:collapse; margin:16px 0 24px; }}
th,td {{ text-align:left; padding:10px; border-bottom:1px solid #30363d; }}
.sev {{ padding:2px 6px; border-radius:999px; }} .sev.high {{ background:#f85149; color:#fff; }} .sev.medium {{ background:#d29922; color:#111; }} .sev.low {{ background:#238636; color:#fff; }}
code {{ color:#8b949e; white-space:pre-wrap; }}
</style>
</head>
<body>
<div class='card'>
<h1>agentkit burn</h1>
<p>Local transcript cost observability, generated by agentkit-cli v{__version__}.</p>
<div class='grid'>
  <div class='metric'><div class='value'>{report.total_cost_usd:.6f}</div><div>Total cost (USD)</div></div>
  <div class='metric'><div class='value'>{report.session_count}</div><div>Sessions</div></div>
  <div class='metric'><div class='value'>{report.turn_count}</div><div>Turns</div></div>
  <div class='metric'><div class='value'>{report.unknown_cost_turns}</div><div>Unknown cost turns</div></div>
</div>
<h2>Where spend goes</h2>
<table><thead><tr><th>Project</th><th>Cost USD</th><th>Turns</th><th>Tool calls</th></tr></thead><tbody>{project_rows}</tbody></table>
<h2>What to fix first</h2>
<ul>{finding_rows}</ul>
<h2>Most expensive sessions</h2>
<table><thead><tr><th>Session</th><th>Project</th><th>Cost USD</th><th>Turns</th><th>Tool calls</th></tr></thead><tbody>{session_rows}</tbody></table>
</div>
</body>
</html>
"""


def render_burn_markdown(report: BurnReport) -> str:
    lines = [
        "## agentkit burn",
        "",
        f"- Total cost: ${report.total_cost_usd:.6f}",
        f"- Sessions: {report.session_count}",
        f"- Turns: {report.turn_count}",
        f"- Unknown cost turns: {report.unknown_cost_turns}",
        "",
        "### Where spend goes",
        "",
        "| Project | Cost USD | Turns | Tool calls |",
        "|---|---:|---:|---:|",
    ]
    for row in report.totals.get("by_project", []):
        lines.append(f"| {row['key']} | {row['cost_usd']:.6f} | {row['turns']} | {row['tool_calls']} |")
    lines += ["", "### What to fix first", ""]
    for finding in report.findings:
        lines.append(f"- **{finding.severity}** {finding.title}")
    return "\n".join(lines)
