"""
Markdown export for incident reports.

Generates clean, incident-ready markdown with:
- Route summary table
- Confidence breakdown
- Alerts and anomalies
- Metadata (time, platform, tool version)

Author: gadwant
"""

from datetime import datetime
from pathlib import Path

from ..models import TraceRun


def export_markdown(trace: TraceRun, output_path: Path):
    """
    Export trace as markdown incident report.

    Args:
        trace: Trace result to export
        output_path: Output markdown file path
    """
    lines = []

    # Header
    lines.append(f"# Traceroute Report: {trace.meta.host}")
    lines.append("")
    lines.append(f"**Date**: {trace.meta.started_at.strftime('%Y-%m-%d %H:%M:%S UTC')}")
    duration_s = (
        (trace.meta.completed_at - trace.meta.started_at).total_seconds()
        if trace.meta.completed_at
        else 0.0
    )
    lines.append(f"**Duration**: {duration_s:.1f}s")
    lines.append(f"**Hops**: {trace.total_hops} ({trace.responded_hops} responded)")
    lines.append(f"**Protocol**: {trace.meta.protocol.upper()}")

    if trace.meta.resolved_ip:
        lines.append(f"**Resolved IP**: {trace.meta.resolved_ip}")

    lines.append("")

    # Route Summary Table
    lines.append("## Route Summary")
    lines.append("")
    lines.append("| Hop | IP | Hostname | RTT | Loss | ASN | Location |")
    lines.append("|-----|----|----|-----|------|-----|----------|")

    for hop in trace.hops:
        hop_num = str(hop.hop)
        ip = hop.ip or "*"
        hostname = hop.hostname or "-"
        if len(hostname) > 30:
            hostname = hostname[:27] + "..."

        if hop.is_timeout:
            rtt = "*"
            loss = "100%"
        else:
            rtt = f"{hop.rtt_avg_ms:.1f}ms" if hop.rtt_avg_ms else "-"
            loss = f"{hop.loss_pct:.0f}%"

        asn = ""
        location = ""
        if hop.geo:
            if hop.geo.asn:
                asn = f"AS{hop.geo.asn}"
                if hop.geo.asn_org:
                    org = hop.geo.asn_org
                    if len(org) > 20:
                        org = org[:17] + "..."
                    asn += f" ({org})"

            if hop.geo.city and hop.geo.country:
                location = f"{hop.geo.city}, {hop.geo.country}"
            elif hop.geo.country:
                location = hop.geo.country

        lines.append(f"| {hop_num} | {ip} | {hostname} | {rtt} | {loss} | {asn} | {location} |")

    lines.append("")

    # Statistics
    lines.append("## Statistics")
    lines.append("")

    rtt_values = [h.rtt_avg_ms for h in trace.hops if h.rtt_avg_ms is not None]
    if rtt_values:
        lines.append(
            f"**RTT**: min {min(rtt_values):.1f}ms, avg {sum(rtt_values) / len(rtt_values):.1f}ms, max {max(rtt_values):.1f}ms"
        )

    lines.append(f"**Packet Loss**: {trace.avg_loss_pct:.1f}% average")
    lines.append("")

    # Alerts
    alerts = trace.get_detour_alerts()
    if alerts:
        lines.append("## Alerts")
        lines.append("")
        for alert in alerts:
            lines.append(f"- ⚠️ {alert}")
        lines.append("")

    # Geo Confidence
    lines.append("## Geo Confidence")
    lines.append("")

    high_conf = sum(1 for h in trace.hops if h.geo and not h.is_private)
    medium_conf = sum(1 for h in trace.hops if h.geo and h.is_private)
    low_conf = sum(1 for h in trace.hops if not h.geo and not h.is_timeout)

    total_responded = trace.responded_hops
    if total_responded > 0:
        lines.append(
            f"- **High confidence**: {high_conf}/{total_responded} hops (public IPs with geo data)"
        )
        lines.append(f"- **Medium confidence**: {medium_conf}/{total_responded} hops (private IPs)")
        lines.append(f"- **Low confidence**: {low_conf}/{total_responded} hops (no geo data)")

    lines.append("")

    # Metadata
    lines.append("## Metadata")
    lines.append("")
    lines.append(f"- **Platform**: {trace.meta.platform_system} {trace.meta.platform_release}")
    lines.append(f"- **Tool**: tracemap v{trace.meta.version}")
    lines.append(f"- **Timestamp**: {datetime.now().isoformat()}")
    lines.append("")

    # Footer
    lines.append("---")
    lines.append("*Generated by [tracemap](https://github.com/adwantg/tracemap)*")

    # Write file
    output_path.write_text("\n".join(lines), encoding="utf-8")
