"""
output/reports.py — VaultHound v1.0.0
JSON, HTML, and plain-text report generators.
"""

from __future__ import annotations

import json
from pathlib import Path

from utils.models import ScanResult, SecretFinding

SEVERITY_COLORS = {
    "critical": "#ff4444",
    "high":     "#ff8c00",
    "medium":   "#ffd700",
    "low":      "#44ff88",
    "info":     "#888888",
}


# ── JSON ──────────────────────────────────────────────────────────────────────

def generate_json_report(result: ScanResult, path: Path) -> Path:
    path.write_text(json.dumps(result.to_dict(), indent=2), encoding="utf-8")
    return path


# ── Text ──────────────────────────────────────────────────────────────────────

def generate_text_report(result: ScanResult, path: Path) -> Path:
    lines = [
        "=" * 70,
        f"  VaultHound v1.0.0 — Secret Scanner Report",
        "=" * 70,
        f"  Target     : {result.target}",
        f"  Mode       : {result.mode.upper()}",
        f"  Started    : {result.start_time}",
        f"  Completed  : {result.end_time}",
        f"  Files      : {len(result.files_scanned)}",
        f"  URLs       : {len(result.urls_scanned)}",
        f"  Git Commits: {result.git_commits_scanned}",
        "=" * 70,
        f"  FINDINGS   : {result.total}  "
        f"(CRITICAL={result.critical_count}  HIGH={result.high_count}  "
        f"MEDIUM={result.medium_count}  LOW={result.low_count})",
        "=" * 70,
        "",
    ]

    if not result.findings:
        lines.append("  No secrets found.")
    else:
        for i, f in enumerate(sorted(result.findings,
                               key=lambda x: __import__('utils.models', fromlist=['Severity']).Severity.rank(x.severity),
                               reverse=True), 1):
            lines += [
                f"[{i}] {f.severity.upper()} — {f.pattern_name}",
                f"    Source  : {f.source}",
                f"    Line    : {f.line_number}",
                f"    Match   : {f.display_match}",
                f"    Context : {f.context}",
                f"    Line    : {f.line_content}",
                "",
            ]

    if result.errors:
        lines += ["", "ERRORS:", *[f"  - {e}" for e in result.errors]]

    path.write_text("\n".join(lines), encoding="utf-8")
    return path


# ── HTML ──────────────────────────────────────────────────────────────────────

def _sev_badge(sev: str) -> str:
    color = SEVERITY_COLORS.get(sev, "#888")
    return (f'<span class="badge" style="background:{color};color:#000;'
            f'padding:2px 8px;border-radius:4px;font-weight:700;font-size:11px;">'
            f'{sev.upper()}</span>')


def generate_html_report(result: ScanResult, path: Path) -> Path:
    from utils.models import Severity

    findings_sorted = sorted(
        result.findings,
        key=lambda f: Severity.rank(f.severity),
        reverse=True
    )

    by_pattern = result.by_pattern
    pattern_rows = "".join(
        f"<tr><td>{p}</td><td style='text-align:center'>{c}</td></tr>"
        for p, c in by_pattern.items()
    )

    finding_rows = ""
    for i, f in enumerate(findings_sorted, 1):
        finding_rows += f"""
        <tr>
            <td>{i}</td>
            <td>{_sev_badge(f.severity)}</td>
            <td style="color:#00d4ff">{f.pattern_name}</td>
            <td><code style="color:#ffd700">{f.display_match}</code></td>
            <td style="word-break:break-all;font-size:12px">{f.source}</td>
            <td style="text-align:center">{f.line_number or '-'}</td>
            <td style="font-size:12px;color:#aaa">{f.context}</td>
        </tr>"""

    error_section = ""
    if result.errors:
        error_rows = "".join(f"<li><code>{e}</code></li>" for e in result.errors)
        error_section = f"""
        <div class="card" style="border-color:#ff4444">
            <h2 style="color:#ff4444">⚠ Errors ({len(result.errors)})</h2>
            <ul style="color:#ccc">{error_rows}</ul>
        </div>"""

    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>VaultHound Report — {result.target}</title>
<style>
  * {{ box-sizing: border-box; margin: 0; padding: 0; }}
  body {{ background: #0a0a0f; color: #e0e0e0; font-family: 'Courier New', monospace; }}
  .header {{ background: linear-gradient(135deg, #0d1117, #1a0a2e);
             padding: 32px; border-bottom: 2px solid #00d4ff; }}
  .header h1 {{ color: #00d4ff; font-size: 28px; letter-spacing: 4px; }}
  .header .sub {{ color: #7c3aed; margin-top: 6px; font-size: 13px; letter-spacing: 2px; }}
  .meta {{ display: flex; gap: 32px; margin-top: 16px; flex-wrap: wrap; }}
  .meta-item {{ color: #aaa; font-size: 13px; }}
  .meta-item span {{ color: #00d4ff; }}
  .stats {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
            gap: 16px; padding: 24px 32px; background: #0d0d1a; }}
  .stat {{ background: #12121f; border: 1px solid #1e1e3a; border-radius: 8px;
           padding: 16px; text-align: center; }}
  .stat .num {{ font-size: 36px; font-weight: 700; }}
  .stat .label {{ color: #888; font-size: 12px; margin-top: 4px; letter-spacing: 1px; }}
  .critical {{ color: #ff4444; }}
  .high {{ color: #ff8c00; }}
  .medium {{ color: #ffd700; }}
  .low {{ color: #44ff88; }}
  .total {{ color: #00d4ff; }}
  .content {{ padding: 24px 32px; }}
  .card {{ background: #12121f; border: 1px solid #1e1e3a; border-radius: 8px;
           padding: 24px; margin-bottom: 24px; }}
  .card h2 {{ color: #00d4ff; margin-bottom: 16px; font-size: 16px; letter-spacing: 2px; }}
  table {{ width: 100%; border-collapse: collapse; font-size: 13px; }}
  th {{ background: #1a1a2e; color: #7c3aed; padding: 10px 12px;
        text-align: left; letter-spacing: 1px; }}
  td {{ padding: 10px 12px; border-bottom: 1px solid #1e1e3a; vertical-align: top; }}
  tr:hover td {{ background: #16162a; }}
  .badge {{ display: inline-block; }}
  .footer {{ text-align: center; padding: 24px; color: #444; font-size: 12px;
             border-top: 1px solid #1e1e3a; }}
</style>
</head>
<body>

<div class="header">
  <h1>⚡ VAULTHOUND</h1>
  <div class="sub">SECRET & CREDENTIAL SCANNER — ExploitCraft</div>
  <div class="meta">
    <div class="meta-item">Target: <span>{result.target}</span></div>
    <div class="meta-item">Mode: <span>{result.mode.upper()}</span></div>
    <div class="meta-item">Started: <span>{result.start_time}</span></div>
    <div class="meta-item">Completed: <span>{result.end_time}</span></div>
    <div class="meta-item">Files: <span>{len(result.files_scanned)}</span></div>
    <div class="meta-item">URLs: <span>{len(result.urls_scanned)}</span></div>
    <div class="meta-item">Git Commits: <span>{result.git_commits_scanned}</span></div>
  </div>
</div>

<div class="stats">
  <div class="stat"><div class="num total">{result.total}</div><div class="label">TOTAL</div></div>
  <div class="stat"><div class="num critical">{result.critical_count}</div><div class="label">CRITICAL</div></div>
  <div class="stat"><div class="num high">{result.high_count}</div><div class="label">HIGH</div></div>
  <div class="stat"><div class="num medium">{result.medium_count}</div><div class="label">MEDIUM</div></div>
  <div class="stat"><div class="num low">{result.low_count}</div><div class="label">LOW</div></div>
</div>

<div class="content">

  <div class="card">
    <h2>📊 FINDINGS BY PATTERN</h2>
    <table>
      <tr><th>Pattern</th><th>Count</th></tr>
      {pattern_rows if pattern_rows else "<tr><td colspan='2' style='color:#555'>No findings</td></tr>"}
    </table>
  </div>

  <div class="card">
    <h2>🔍 ALL FINDINGS ({result.total})</h2>
    <table>
      <tr>
        <th>#</th><th>Severity</th><th>Pattern</th><th>Match</th>
        <th>Source</th><th>Line</th><th>Context</th>
      </tr>
      {finding_rows if finding_rows else "<tr><td colspan='7' style='color:#555;text-align:center'>No secrets found — target appears clean</td></tr>"}
    </table>
  </div>

  {error_section}

</div>

<div class="footer">
  VaultHound v1.0.0 — ExploitCraft | <a href="https://github.com/ExploitCraft/VaultHound" style="color:#7c3aed">github.com/ExploitCraft/VaultHound</a>
  <br>⚠ Use only against targets you own or have explicit written permission to test.
</div>

</body>
</html>"""

    path.write_text(html, encoding="utf-8")
    return path
