"""Report generation — Markdown and HTML output."""

from __future__ import annotations

from pathlib import Path

from jinja2 import BaseLoader, Environment

from rc_insights.models import HealthReport

SEVERITY_EMOJI = {
    "critical": "🔴",
    "warning": "🟡",
    "positive": "🟢",
    "info": "🔵",
}

TREND_EMOJI = {
    "up": "📈",
    "down": "📉",
    "stable": "➡️",
}


def render_markdown(report: HealthReport) -> str:
    """Render a health report as Markdown."""
    lines: list[str] = []

    # Header
    lines.append("# 📊 Subscription Health Report")
    lines.append("")
    lines.append(f"**Project:** `{report.project_id}`")
    lines.append(
        f"**Period:** {report.period_start.isoformat()} → {report.period_end.isoformat()}"
    )
    lines.append(f"**Generated:** {report.generated_at.strftime('%Y-%m-%d %H:%M')}")
    lines.append("")

    # Health Score
    score = report.overall_health_score
    bar = "█" * int(score / 5) + "░" * (20 - int(score / 5))
    if score >= 70:
        grade = "Healthy ✅"
    elif score >= 40:
        grade = "Mixed ⚠️"
    else:
        grade = "Critical 🚨"

    lines.append(f"## Health Score: {score:.0f}/100 — {grade}")
    lines.append("```")
    lines.append(f"[{bar}] {score:.0f}%")
    lines.append("```")
    lines.append("")

    # Summary
    lines.append("### Executive Summary")
    lines.append("")
    lines.append(report.summary)
    lines.append("")

    # Overview Metrics
    if report.overview:
        lines.append("## 📋 Key Metrics")
        lines.append("")
        lines.append("| Metric | Value | Period |")
        lines.append("|--------|-------|--------|")
        for m in report.overview.metrics:
            unit = f" {m.unit}" if m.unit and m.unit != "number" else ""
            lines.append(f"| {m.name} | {m.value:,.2f}{unit} | {m.period} |")
        lines.append("")

    # Insights
    if report.insights:
        lines.append("## 🧠 AI Insights")
        lines.append("")

        # Group by severity
        for severity in ["critical", "warning", "positive", "info"]:
            group = [i for i in report.insights if i.severity == severity]
            if not group:
                continue

            emoji = SEVERITY_EMOJI[severity]
            lines.append(f"### {emoji} {severity.title()}")
            lines.append("")

            for insight in group:
                trend = f" {TREND_EMOJI.get(insight.trend or '', '')}" if insight.trend else ""
                metric = f" ({insight.metric_value})" if insight.metric_value else ""
                lines.append(f"#### {insight.title}{metric}{trend}")
                lines.append("")
                lines.append(insight.description)
                lines.append("")
                lines.append(f"> **Recommendation:** {insight.recommendation}")
                lines.append("")

    # Chart Summaries
    summaries = report.chart_summaries
    if summaries:
        lines.append("## 📈 Charts Summary")
        lines.append("")
        lines.append("| Chart | Latest | Min | Max | Trend |")
        lines.append("|-------|--------|-----|-----|-------|")

        for row in summaries:
            lines.append(
                f"| {row['name']} | {row['latest']} | {row['vmin']} | {row['vmax']} | {row['trend']} |"
            )

        lines.append("")

    # Footer
    lines.append("---")
    lines.append(
        "*Generated by [RC Insights](https://github.com/arimetabot/rc-insights) — "
        "AI-powered subscription analytics for RevenueCat*"
    )

    return "\n".join(lines)


HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Subscription Health Report — RC Insights</title>
<style>
:root {
    --bg: #0f1117;
    --surface: #1a1d27;
    --surface-2: #242833;
    --text: #e4e6eb;
    --text-muted: #8b8fa3;
    --accent: #6366f1;
    --green: #22c55e;
    --yellow: #eab308;
    --red: #ef4444;
    --blue: #3b82f6;
    --border: #2d3148;
    --font: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: var(--font);
    background: var(--bg);
    color: var(--text);
    line-height: 1.6;
    padding: 2rem;
    max-width: 900px;
    margin: 0 auto;
}
h1 { font-size: 1.75rem; margin-bottom: 0.5rem; }
h2 { font-size: 1.25rem; margin: 2rem 0 1rem; color: var(--text); }
h3 { font-size: 1rem; margin: 1.5rem 0 0.5rem; }
.meta { color: var(--text-muted); font-size: 0.85rem; margin-bottom: 2rem; }
.score-card {
    background: var(--surface);
    border-radius: 12px;
    padding: 1.5rem;
    margin: 1.5rem 0;
    border: 1px solid var(--border);
    text-align: center;
}
.score-value {
    font-size: 3rem;
    font-weight: 700;
    background: linear-gradient(135deg, var(--accent), var(--blue));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
.score-bar {
    width: 100%;
    height: 8px;
    background: var(--surface-2);
    border-radius: 4px;
    margin-top: 1rem;
    overflow: hidden;
}
.score-fill {
    height: 100%;
    border-radius: 4px;
    transition: width 1s ease;
}
.summary {
    background: var(--surface);
    padding: 1.25rem;
    border-radius: 8px;
    border-left: 4px solid var(--accent);
    margin: 1rem 0;
    font-size: 0.95rem;
}
.metrics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 1rem;
    margin: 1rem 0;
}
.metric-card {
    background: var(--surface);
    border-radius: 8px;
    padding: 1rem;
    border: 1px solid var(--border);
}
.metric-value { font-size: 1.5rem; font-weight: 600; }
.metric-name { color: var(--text-muted); font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.05em; }
.insight {
    background: var(--surface);
    border-radius: 8px;
    padding: 1rem 1.25rem;
    margin: 0.75rem 0;
    border-left: 4px solid;
}
.insight.critical { border-color: var(--red); }
.insight.warning { border-color: var(--yellow); }
.insight.positive { border-color: var(--green); }
.insight.info { border-color: var(--blue); }
.insight-title { font-weight: 600; margin-bottom: 0.25rem; }
.insight-desc { color: var(--text-muted); font-size: 0.9rem; margin-bottom: 0.5rem; }
.insight-rec {
    font-size: 0.85rem;
    padding: 0.5rem 0.75rem;
    background: var(--surface-2);
    border-radius: 6px;
    margin-top: 0.5rem;
}
table {
    width: 100%;
    border-collapse: collapse;
    margin: 1rem 0;
    font-size: 0.9rem;
}
th, td {
    padding: 0.5rem 0.75rem;
    text-align: left;
    border-bottom: 1px solid var(--border);
}
th { color: var(--text-muted); font-weight: 500; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.05em; }
footer {
    margin-top: 3rem;
    padding-top: 1rem;
    border-top: 1px solid var(--border);
    color: var(--text-muted);
    font-size: 0.8rem;
    text-align: center;
}
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>📊 Subscription Health Report</h1>
<div class="meta">
    Project: <code>{{ report.project_id }}</code> &middot;
    {{ report.period_start }} → {{ report.period_end }} &middot;
    Generated {{ report.generated_at.strftime('%Y-%m-%d %H:%M') }}
</div>

<div class="score-card">
    <div class="score-value">{{ report.overall_health_score|int }}/100</div>
    <div style="color: var(--text-muted); margin-top: 0.25rem;">
        {% if report.overall_health_score >= 70 %}Healthy ✅
        {% elif report.overall_health_score >= 40 %}Mixed Signals ⚠️
        {% else %}Needs Attention 🚨{% endif %}
    </div>
    <div class="score-bar">
        <div class="score-fill" style="width: {{ report.overall_health_score }}%;
            background: {% if report.overall_health_score >= 70 %}var(--green)
            {% elif report.overall_health_score >= 40 %}var(--yellow)
            {% else %}var(--red){% endif %};"></div>
    </div>
</div>

<div class="summary">{{ report.summary }}</div>

{% if report.overview %}
<h2>📋 Key Metrics</h2>
<div class="metrics-grid">
{% for m in report.overview.metrics %}
    <div class="metric-card">
        <div class="metric-name">{{ m.name }}</div>
        <div class="metric-value">
            {% if m.unit == '$' %}${% endif %}{{ "%.2f"|format(m.value) }}{% if m.unit == '%' %}%{% endif %}
        </div>
        <div style="color: var(--text-muted); font-size: 0.75rem;">{{ m.period }}</div>
    </div>
{% endfor %}
</div>
{% endif %}

{% if report.insights %}
<h2>🧠 AI Insights</h2>
{% for insight in report.insights %}
<div class="insight {{ insight.severity }}">
    <div class="insight-title">
        {% if insight.severity == 'critical' %}🔴
        {% elif insight.severity == 'warning' %}🟡
        {% elif insight.severity == 'positive' %}🟢
        {% else %}🔵{% endif %}
        {{ insight.title }}
        {% if insight.metric_value %}<span style="color: var(--text-muted);"> ({{ insight.metric_value }})</span>{% endif %}
        {% if insight.trend == 'up' %} 📈{% elif insight.trend == 'down' %} 📉{% endif %}
    </div>
    <div class="insight-desc">{{ insight.description }}</div>
    <div class="insight-rec">💡 {{ insight.recommendation }}</div>
</div>
{% endfor %}
{% endif %}

{% set summaries = report.chart_summaries %}
{% if summaries %}
<h2>📈 Charts Summary</h2>
<table>
    <thead>
        <tr><th>Chart</th><th>Latest</th><th>Min</th><th>Max</th><th>Trend</th></tr>
    </thead>
    <tbody>
        {% for row in summaries %}
        <tr>
            <td>{{ row.name }}</td>
            <td>{{ row.latest }}</td>
            <td>{{ row.vmin }}</td>
            <td>{{ row.vmax }}</td>
            <td>{{ row.trend }}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>
{% endif %}

<footer>
    Generated by <a href="https://github.com/arimetabot/rc-insights">RC Insights</a> —
    AI-powered subscription analytics for RevenueCat
</footer>
</body>
</html>"""


def render_html(report: HealthReport) -> str:
    """Render a health report as a styled HTML page."""
    env = Environment(loader=BaseLoader(), autoescape=True)
    template = env.from_string(HTML_TEMPLATE)
    return template.render(report=report)


def save_report(
    report: HealthReport,
    output_dir: str | Path = ".",
    *,
    formats: list[str] | None = None,
) -> list[Path]:
    """Save report in multiple formats.

    Args:
        report: The health report to save.
        output_dir: Directory to save files in.
        formats: List of formats to generate ("md", "html"). Defaults to both.

    Returns:
        List of generated file paths.
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    formats = formats or ["md", "html"]

    timestamp = report.generated_at.strftime("%Y%m%d_%H%M")
    files: list[Path] = []

    if "md" in formats:
        md_path = output_dir / f"report_{timestamp}.md"
        md_path.write_text(render_markdown(report))
        files.append(md_path)

    if "html" in formats:
        html_path = output_dir / f"report_{timestamp}.html"
        html_path.write_text(render_html(report))
        files.append(html_path)

    return files
