"""Reporter - outputs JSON and HTML reports."""
import json
from pathlib import Path
import os
from apk_analyzer.models import AnalysisResult

_HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>APK SDK Analysis Report</title>
<style>
:root{--bg:#0f1117;--card:#1a1d27;--border:#2d3148;--accent:#7c6af7;--green:#4ade80;--yellow:#fbbf24;--red:#f87171;--text:#e2e8f0;--muted:#8892a4}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:14px;line-height:1.6}
.container{max-width:1200px;margin:0 auto;padding:24px}
header{background:linear-gradient(135deg,#1a1d27,#1e2236);border:1px solid var(--border);border-radius:12px;padding:24px;margin-bottom:24px}
header h1{font-size:22px;font-weight:700;color:var(--accent);margin-bottom:8px}
.meta-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;margin-top:16px}
.meta-item{background:#0f1117;border-radius:8px;padding:12px}
.meta-item .label{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.5px}
.meta-item .value{font-size:16px;font-weight:600;margin-top:2px}
.summary-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-bottom:24px}
.summary-card{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:16px;text-align:center}
.summary-card .num{font-size:28px;font-weight:700;color:var(--accent)}
.summary-card .lbl{color:var(--muted);font-size:11px;margin-top:4px}
.section{background:var(--card);border:1px solid var(--border);border-radius:10px;margin-bottom:16px;overflow:hidden}
.section-header{padding:14px 18px;background:#1e2236;display:flex;align-items:center;justify-content:space-between;cursor:pointer;user-select:none}
.section-header h2{font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px}
.badge{display:inline-flex;align-items:center;justify-content:center;min-width:22px;height:22px;border-radius:11px;background:var(--accent);color:#fff;font-size:11px;font-weight:700;padding:0 6px}
.sdk-grid{display:grid;gap:0}
.sdk-row{padding:12px 18px;border-top:1px solid var(--border);display:grid;grid-template-columns:1fr auto auto 120px;gap:12px;align-items:start;transition:background .15s}
.sdk-row:hover{background:#1e2236}
.sdk-name{font-weight:600;font-size:13px}
.sdk-desc{color:var(--muted);font-size:11px;margin-top:2px}
.sdk-vendor{color:var(--muted);font-size:11px}
.version-tag{background:#1e3a2f;color:var(--green);border-radius:6px;padding:2px 8px;font-size:11px;font-family:monospace;white-space:nowrap;text-align:center}
.version-unknown{background:#1e2236;color:var(--muted);border-radius:6px;padding:2px 8px;font-size:11px;text-align:center}
.risk-tag{border-radius:6px;padding:2px 8px;font-size:11px;font-weight:600;text-align:center}
.risk-low{background:#1a2e1a;color:var(--green)}.risk-medium{background:#2d2500;color:var(--yellow)}.risk-high{background:#2d1a1a;color:var(--red)}.risk-unknown{background:#1e2236;color:var(--muted)}
.conf-high{color:var(--green)}.conf-medium{color:var(--yellow)}.conf-low{color:var(--red)}
.evidence{font-size:11px;color:var(--muted);margin-top:6px}
.evidence span{background:#0f1117;border-radius:4px;padding:1px 6px;margin:1px;display:inline-block;font-family:monospace}
.filter-bar{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap}
.filter-btn{background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:20px;padding:5px 14px;font-size:12px;cursor:pointer;transition:all .15s}
.filter-btn.active,.filter-btn:hover{background:var(--accent);border-color:var(--accent);color:#fff}
.search-bar{background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:8px;padding:8px 14px;font-size:13px;width:100%;margin-bottom:16px;outline:none}
.search-bar:focus{border-color:var(--accent)}
footer{text-align:center;color:var(--muted);font-size:12px;margin-top:32px;padding:16px 0}
.perm-list{padding:8px 18px 12px;display:flex;flex-wrap:wrap;gap:4px}
.perm-tag{background:#0f1117;border-radius:4px;padding:2px 8px;font-size:11px;font-family:monospace;color:var(--muted)}
</style>
</head>
<body>
<div class="container">
<header>
  <h1>&#128269; APK SDK Analysis Report</h1>
  <div id="apk-meta"></div>
</header>
<div class="summary-grid" id="summary-grid"></div>
<input class="search-bar" type="text" placeholder="Search SDK name, vendor, package..." id="search-input" oninput="filterSDKs()">
<div class="filter-bar" id="filter-bar"></div>
<div id="sdk-sections"></div>
<footer>Generated by apk-analyzer &bull; <span id="gen-time"></span></footer>
</div>
<script>
const D = __REPORT_DATA__;
const cat_icons={"push":"&#128244;","ads":"&#128176;","social":"&#128101;","payment":"&#128179;","network":"&#127760;","storage":"&#128190;","security":"&#128737;","media":"&#127916;","ui":"&#127912;","map":"&#128506;","bytedance_internal":"&#128640;","other":"&#129760;"};
function riskClass(r){return"risk-"+(r||"unknown")}
function confClass(c){return"conf-"+(c||"low")}

function renderMeta(){
  const a=D.apk_info,m=D.meta;
  document.getElementById("apk-meta").innerHTML=`<div class="meta-grid">
    <div class="meta-item"><div class="label">Package</div><div class="value" style="font-size:13px">${a.package_name}</div></div>
    <div class="meta-item"><div class="label">App Name</div><div class="value">${a.app_name||"Unknown"}</div></div>
    <div class="meta-item"><div class="label">Version</div><div class="value">${a.version_name} (${a.version_code})</div></div>
    <div class="meta-item"><div class="label">SDK Range</div><div class="value">${a.min_sdk} – ${a.target_sdk}</div></div>
    <div class="meta-item"><div class="label">DEX Files</div><div class="value">${a.dex_count}</div></div>
    <div class="meta-item"><div class="label">Native Libs</div><div class="value">${(a.native_libs||[]).length}</div></div>
    <div class="meta-item"><div class="label">Permissions</div><div class="value">${(a.permissions||[]).length}</div></div>
    <div class="meta-item"><div class="label">Analysis Time</div><div class="value">${m.analysis_duration_seconds}s</div></div>
  </div>`;
  document.getElementById("gen-time").textContent=m.analysis_time;
}

function renderSummary(){
  const s=D.summary;
  const cards=[
    {num:s.total_detected,lbl:"SDKs Detected"},
    {num:s.versions_extracted,lbl:"Versions Found"},
    {num:s.high_risk_count,lbl:"High Risk"},
    {num:s.medium_risk_count,lbl:"Medium Risk"},
    {num:Object.keys(s.by_category).length,lbl:"Categories"},
  ];
  document.getElementById("summary-grid").innerHTML=cards.map(c=>
    `<div class="summary-card"><div class="num">${c.num}</div><div class="lbl">${c.lbl}</div></div>`).join("");
}

let activeFilter="all";
function buildFilters(){
  const cats=["all",...Object.keys(D.summary.by_category).sort()];
  document.getElementById("filter-bar").innerHTML=cats.map(c=>
    `<button class="filter-btn${c==="all"?" active":""}" onclick="setFilter('${c}')">${c==="all"?"All":(cat_icons[c]||"")+" "+c} ${c!=="all"?"("+D.summary.by_category[c]+")":""}</button>`).join("");
}

function setFilter(cat){
  activeFilter=cat;
  document.querySelectorAll(".filter-btn").forEach(b=>{b.classList.toggle("active",b.textContent.includes(cat==="all"?"All":cat))});
  filterSDKs();
}

function filterSDKs(){
  const q=document.getElementById("search-input").value.toLowerCase();
  document.querySelectorAll(".sdk-row").forEach(row=>{
    const cat=row.dataset.cat;
    const text=row.dataset.text||"";
    const catOk=activeFilter==="all"||cat===activeFilter;
    const searchOk=!q||text.includes(q);
    row.style.display=(catOk&&searchOk)?"grid":"none";
  });
  document.querySelectorAll(".section").forEach(sec=>{
    const visible=[...sec.querySelectorAll(".sdk-row")].some(r=>r.style.display!=="none");
    sec.style.display=visible?"":"none";
  });
}

function renderSDKs(){
  const byCat={};
  D.detected_sdks.forEach(s=>{(byCat[s.category]=byCat[s.category]||[]).push(s);});
  const out=[];
  for(const [cat,sdks] of Object.entries(byCat).sort()){
    const rows=sdks.map(s=>{
      const ev=s.detection_evidence||{};
      const allPkgs=[...(ev.matched_packages||[]),...(ev.matched_natives||[]),...(ev.matched_manifest_services||[])];
      const pkgTags=allPkgs.slice(0,3).map(p=>`<span>${p}</span>`).join("");
      const verTag=s.version?`<div class="version-tag">${s.version}</div>`:`<div class="version-unknown">unknown</div>`;
      const rTag=`<div class="risk-tag ${riskClass(s.risk?.privacy_risk)}">${s.risk?.privacy_risk||"?"}</div>`;
      const searchText=[s.name,s.vendor,s.description,...allPkgs].join(" ").toLowerCase();
      return `<div class="sdk-row" data-cat="${cat}" data-text="${searchText.replace(/"/g,"&quot;")}">
        <div>
          <div class="sdk-name">${s.name} <span class="${confClass(s.confidence)}" style="font-size:10px">(${s.confidence})</span></div>
          <div class="sdk-vendor">${s.vendor||""}</div>
          <div class="sdk-desc">${s.description||""}</div>
          ${allPkgs.length?`<div class="evidence">${pkgTags}</div>`:""}
        </div>
        <div></div>
        ${verTag}
        ${rTag}
      </div>`;
    });
    out.push(`<div class="section">
      <div class="section-header" onclick="toggleSection(this)">
        <h2>${cat_icons[cat]||"📦"} ${cat} <span class="badge">${sdks.length}</span></h2>
        <span>&#9660;</span>
      </div>
      <div class="sdk-grid">${rows.join("")}</div>
    </div>`);
  }
  document.getElementById("sdk-sections").innerHTML=out.join("");
}

function toggleSection(hdr){
  const grid=hdr.nextElementSibling;
  grid.style.display=grid.style.display==="none"?"grid":"none";
}

renderMeta(); renderSummary(); buildFilters(); renderSDKs();
</script>
</body>
</html>
"""


class Reporter:
    def __init__(self, result: AnalysisResult, template_path: str = None):
        self.result = result
        self.template_path = template_path

    def write_json(self, path: Path):
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            json.dump(self.result.to_dict(), f, ensure_ascii=False, indent=2)

    def write_html(self, path: Path):
        path.parent.mkdir(parents=True, exist_ok=True)
        template = _HTML_TEMPLATE
        if self.template_path and Path(self.template_path).exists():
            template = Path(self.template_path).read_text(encoding="utf-8")
        data_json = json.dumps(self.result.to_dict(), ensure_ascii=False)
        html = template.replace("__REPORT_DATA__", data_json)
        with open(path, "w", encoding="utf-8") as f:
            f.write(html)
