"""Export reporter — JSON and HTML output."""
import json
from ..models import ToilReport


def to_dict(report: ToilReport) -> dict:
    return {
        "total_tasks": report.total_tasks,
        "total_annual_hours": round(report.total_annual_hours, 1),
        "automatable_hours": round(report.automatable_hours, 1),
        "automation_coverage": round(report.automation_coverage, 1),
        "health_score": report.health_score,
        "grade": report.grade,
        "summary": {
            "critical": report.critical_count,
            "high": report.high_count,
            "medium": report.medium_count,
            "low": report.low_count,
            "info": report.info_count,
        },
        "tasks": [
            {
                "name": t.name,
                "category": t.category.value,
                "frequency": t.frequency.value,
                "annual_hours": round(t.annual_hours, 1),
                "automation_roi_months": round(t.automation_roi_months, 1) if t.automation_roi_months < 1000 else None,
                "is_automatable": t.is_automatable,
            }
            for t in report.tasks
        ],
        "findings": [
            {
                "rule_id": f.rule_id,
                "title": f.title,
                "severity": f.severity.value,
                "task_name": f.task_name,
                "category": f.category,
                "description": f.description,
                "recommendation": f.recommendation,
            }
            for f in report.findings
        ],
    }


def to_json(report: ToilReport) -> str:
    return json.dumps(to_dict(report), indent=2)


def to_html(report: ToilReport) -> str:
    d = to_dict(report)
    rows = ""
    for f in d["findings"]:
        color = {"critical": "#dc3545", "high": "#fd7e14", "medium": "#ffc107", "low": "#17a2b8"}.get(f["severity"], "#6c757d")
        rows += f"""<tr>
<td>{f['rule_id']}</td>
<td style="color:{color};font-weight:bold">{f['severity'].upper()}</td>
<td>{f['task_name']}</td>
<td>{f['description']}</td>
<td>{f['recommendation']}</td>
</tr>"""
    return f"""<!DOCTYPE html>
<html><head><title>Toil Tracker Report</title>
<style>body{{font-family:sans-serif;margin:2em}}table{{border-collapse:collapse;width:100%}}
th,td{{border:1px solid #ddd;padding:8px;text-align:left}}th{{background:#f4f4f4}}</style></head>
<body><h1>Toil Tracker Report</h1>
<p><b>Tasks:</b> {d['total_tasks']} | <b>Toil:</b> {d['total_annual_hours']}h/year | <b>Automatable:</b> {d['automatable_hours']}h/year | <b>Score:</b> {d['health_score']}/100 (Grade {d['grade']})</p>
<table><tr><th>Rule</th><th>Severity</th><th>Task</th><th>Issue</th><th>Recommendation</th></tr>
{rows}</table></body></html>"""
