"""Reporter - outputs JSON and HTML reports."""
import html as html_module
import json
from pathlib import Path

from apk_analyzer.models import AnalysisResult


def _render_string_section_html(result: AnalysisResult) -> str:
    """Pre-render string section server-side so it's visible even if JS fails."""
    info = result.apk_info
    string_dirs = getattr(info, "string_dirs", None) or {}
    string_locales = getattr(info, "string_locales", None) or []
    string_support = getattr(info, "string_support", None) or "unknown"
    resources = sorted(string_dirs.keys())
    common_locales = ["default", "en", "zh", "zh-CN", "zh-TW", "ja", "ko", "de", "fr", "es", "pt", "pt-BR", "ru", "ar"]
    displayed = [l for l in common_locales if l in string_locales]
    if not resources:
        return (
            '<div class="section-header"><h2>&#127760; String Resource Language Matrix</h2></div>'
            '<div class="abi-conclusion">Conclusion: <strong>'
            + html_module.escape(str(string_support))
            + "</strong></div>"
            '<div class="perm-list"><span class="perm-tag">No string resources found</span></div>'
        )
    rows = []
    for res in resources[:10]:
        locales = string_dirs.get(res, [])
        cells = "".join(
            f'<td class="{"abi-yes" if loc in locales else "abi-no"}">{"✅" if loc in locales else "❌"}</td>'
            for loc in displayed
        )
        other = [l for l in locales if l not in displayed]
        other_cell = f'<td class="abi-other">{html_module.escape(", ".join(other))}</td>' if other else "<td class=\"abi-other\">-</td>"
        rows.append(f"<tr><td>{html_module.escape(res)}</td>{cells}{other_cell}</tr>")
    header_cells = "".join(f"<th>{html_module.escape(l)}</th>" for l in displayed)
    more = f'<div class="abi-row-hint">Showing first 10 of {len(resources)} rows</div>' if len(resources) > 10 else ""
    return (
        '<div class="section-header"><h2>&#127760; String Resource Language Matrix</h2></div>'
        f'<div class="abi-conclusion">Conclusion: <strong>{html_module.escape(str(string_support))}</strong></div>'
        f"{more}"
        '<div class="abi-matrix-wrap"><table class="abi-table">'
        f"<thead><tr><th>String Resource</th>{header_cells}<th>Other Locales</th></tr></thead>"
        f"<tbody>{''.join(rows)}</tbody></table></div>"
    )

_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}
.evidence .rule-package{background:#1e3a5f;color:#60a5fa;border-radius:4px;padding:1px 6px;margin:1px;display:inline-block;font-family:monospace}
.evidence .rule-native{background:#1e3a2f;color:#4ade80;border-radius:4px;padding:1px 6px;margin:1px;display:inline-block;font-family:monospace}
.evidence .rule-manifest{background:#3d2a1e;color:#fb923c;border-radius:4px;padding:1px 6px;margin:1px;display:inline-block;font-family:monospace}
.evidence .rule-string{background:#231f3b;color:#c4b5fd;border-radius:4px;padding:1px 6px;margin:1px;display:inline-block;font-family:monospace}
.evidence .rule-other{background:#2d3148;color:#94a3b8;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)}
.abi-matrix-wrap{padding:12px 18px 16px;overflow-x:auto}
.abi-conclusion{padding:12px 18px 0;color:var(--text);font-size:13px}
.abi-conclusion strong{color:var(--accent)}
.abi-table{width:100%;border-collapse:collapse;min-width:520px}
.abi-table th,.abi-table td{border-top:1px solid var(--border);padding:8px 10px;font-size:12px;text-align:center}
.abi-table th:first-child,.abi-table td:first-child{text-align:left;font-family:monospace}
.abi-table.abi-table-collapsed tbody tr:nth-child(n+6){display:none}
.abi-yes{color:var(--green);font-weight:700}
.abi-no{color:var(--red);font-weight:700}
.abi-other{color:var(--muted);font-family:monospace}
.abi-actions{padding:8px 18px 0;display:flex;align-items:center;justify-content:space-between;gap:12px}
.abi-row-hint{color:var(--muted);font-size:11px}
.abi-toggle-btn{background:#1e2236;border:1px solid var(--border);color:var(--text);border-radius:6px;padding:4px 10px;font-size:11px;cursor:pointer}
.abi-toggle-btn:hover{border-color:var(--accent);color:var(--accent)}
</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>
<div class="section" id="native-abi-section"></div>
<div class="section" id="resource-dpi-section"></div>
<div class="section" id="resource-string-section">__STRING_SECTION_HTML__</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;"};
const RULE_TO_CAT={"package_prefixes":"package","native_libs":"native","manifest_services":"manifest","manifest_receivers":"manifest","manifest_activities":"manifest","manifest_providers":"manifest","manifest_actions":"manifest","string_patterns":"string"};
function ruleClass(rule){
  const t=(String(rule).split(":")[0]||"").replace(/[^a-z0-9_]/g,"");
  return RULE_TO_CAT[t]?"rule-"+RULE_TO_CAT[t]:"rule-other";
}
function ruleDisplayText(rule){
  const s=String(rule);
  const idx=s.indexOf(":");
  return idx>=0?s.slice(idx+1):s;
}
function ruleTooltip(rule){
  const s=String(rule);
  const idx=s.indexOf(":");
  return idx>=0?s.slice(0,idx):s;
}
function riskClass(r){return"risk-"+(r||"unknown")}
function confClass(c){return"conf-"+(c||"low")}
function escapeHTML(s){return String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}
function formatFileSize(bytes){
  const n=Number(bytes);
  if(!Number.isFinite(n)||n<0)return"Unknown";
  if(n===0)return"0 B";
  const units=["B","KB","MB","GB","TB"];
  const i=Math.min(Math.floor(Math.log(n)/Math.log(1024)),units.length-1);
  const v=n/Math.pow(1024,i);
  return `${v>=10||i===0?Math.round(v):v.toFixed(1)} ${units[i]}`;
}

function renderMeta(){
  const a=D.apk_info,m=D.meta;
  const schemes=(a.signing_schemes||[]).join("/")||"unsigned";
  const signingOrg=(a.signing_organization||((a.signing_certificates||[])[0]?.organization)||"unknown");
  const signerSha=((a.signing_certificates||[])[0]?.sha256||"").toUpperCase();
  const signerShort=signerSha?`${signerSha.slice(0,16)}...`:"unknown";
  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(min/target)</div><div class="value">${a.min_sdk}/${a.target_sdk}</div></div>
    <div class="meta-item"><div class="label">APK Size</div><div class="value">${formatFileSize(a.file_size_bytes)}</div></div>
    <div class="meta-item"><div class="label">ABI Support</div><div class="value">${a.abi_support||"unknown"}</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">Signing Organization</div><div class="value">${signingOrg}</div></div>
    <div class="meta-item"><div class="label">Signing Schemes</div><div class="value">${schemes}</div></div>
    <div class="meta-item"><div class="label">Signer SHA256</div><div class="value" style="font-size:12px">${signerShort}</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 renderNativeAbiMatrix(){
  const a=D.apk_info||{};
  const arches=a.native_lib_arches||{};
  const descs=a.native_lib_descriptions||{};
  const libs=Object.keys(arches).sort();
  const visibleLimit=5;
  const sec=document.getElementById("native-abi-section");
  const conclusion=a.abi_support||"Other";
  if(!libs.length){
    sec.innerHTML=`<div class="section-header"><h2>&#129513; SO Architecture Matrix</h2></div>
      <div class="abi-conclusion">Conclusion: <strong>${escapeHTML(conclusion)}</strong></div>
      <div class="perm-list"><span class="perm-tag">No .so files found</span></div>`;
    return;
  }
  const rows=libs.map(lib=>{
    const abis=arches[lib]||[];
    const has32=abis.includes("armeabi-v7a");
    const has64=abis.includes("arm64-v8a");
    const desc=descs[lib]||"";
    const nameCell=desc
      ? `<div style="font-weight:600">${escapeHTML(lib)}</div><div class="sdk-desc">${escapeHTML(desc)}</div>`
      : `${escapeHTML(lib)}`;
    return `<tr>
      <td>${nameCell}</td>
      <td class="${has32?"abi-yes":"abi-no"}">${has32?"✅":"❌"}</td>
      <td class="${has64?"abi-yes":"abi-no"}">${has64?"✅":"❌"}</td>
      <td class="abi-other">${escapeHTML(abis.join(", ")||"-")}</td>
    </tr>`;
  }).join("");
  const hasMoreRows=libs.length>visibleLimit;
  const actions=hasMoreRows
    ? `<div class="abi-actions">
        <span class="abi-row-hint">Showing first ${visibleLimit} of ${libs.length} rows</span>
        <button class="abi-toggle-btn" data-total-rows="${libs.length}" data-visible-limit="${visibleLimit}" onclick="toggleAbiMatrixRows(this)">Expand</button>
      </div>`
    : "";
  sec.innerHTML=`<div class="section-header"><h2>&#129513; SO Architecture Matrix</h2></div>
    <div class="abi-conclusion">Conclusion: <strong>${escapeHTML(conclusion)}</strong></div>
    ${actions}
    <div class="abi-matrix-wrap">
      <table class="abi-table${hasMoreRows?" abi-table-collapsed":""}">
        <thead>
          <tr><th>SO File</th><th>armeabi-v7a</th><th>arm64-v8a</th><th>Detected ABIs</th></tr>
        </thead>
        <tbody>${rows}</tbody>
      </table>
    </div>`;
}

function renderResourceDpiMatrix(){
  const a=D.apk_info||{};
  const resourceDirs=a.resource_dirs||{};
  const resources=Object.keys(resourceDirs).sort();
  const visibleLimit=5;
  const sec=document.getElementById("resource-dpi-section");
  const conclusion=a.dpi_support||"unknown";
  if(!resources.length){
    sec.innerHTML=`<div class="section-header"><h2>&#127912; Image Resource DPI Matrix</h2></div>
      <div class="abi-conclusion">Conclusion: <strong>${escapeHTML(conclusion)}</strong></div>
      <div class="perm-list"><span class="perm-tag">No image resources found</span></div>`;
    return;
  }
  const allDpis=a.resource_dpis||[];
  const commonDpis=["ldpi","mdpi","tvdpi","hdpi","xhdpi","xxhdpi","xxxhdpi","nodpi","anydpi"];
  const displayedDpis=commonDpis.filter(d=>allDpis.includes(d));
  const refs=D.resource_data?.resource_references||[];
  const refSet=new Set(refs);
  const rows=resources.map(res=>{
    const dpis=resourceDirs[res]||[];
    const cells=displayedDpis.map(dpi=>{
      const has=dpis.includes(dpi);
      return `<td class="${has?"abi-yes":"abi-no"}">${has?"✅":"❌"}</td>`;
    }).join("");
    const otherDpis=dpis.filter(d=>!displayedDpis.includes(d));
    const otherCell=otherDpis.length?`<td class="abi-other">${escapeHTML(otherDpis.join(", ")||"-")}</td>`:`<td class="abi-other">-</td>`;
    const resName=res.split("/").pop()||res;
    const isReferenced=refSet.has(resName)||refs.some(r=>res.includes(r)||r.includes(resName));
    const refCell=`<td class="${isReferenced?"abi-yes":"abi-no"}" style="font-weight:600">${isReferenced?"✅ Referenced":"❌ Unused"}</td>`;
    return `<tr>
      <td>${escapeHTML(res)}</td>
      ${cells}
      ${otherCell}
      ${refCell}
    </tr>`;
  }).join("");
  const hasMoreRows=resources.length>visibleLimit;
  const actions=hasMoreRows
    ? `<div class="abi-actions">
        <span class="abi-row-hint">Showing first ${visibleLimit} of ${resources.length} rows</span>
        <button class="abi-toggle-btn" data-total-rows="${resources.length}" data-visible-limit="${visibleLimit}" onclick="toggleDpiMatrixRows(this)">Expand</button>
      </div>`
    : "";
  const headerCells=displayedDpis.map(d=>`<th>${d}</th>`).join("");
  sec.innerHTML=`<div class="section-header"><h2>&#127912; Image Resource DPI Matrix</h2></div>
    <div class="abi-conclusion">Conclusion: <strong>${escapeHTML(conclusion)}</strong></div>
    ${actions}
    <div class="abi-matrix-wrap">
      <table class="abi-table${hasMoreRows?" abi-table-collapsed":""}">
        <thead>
          <tr><th>Resource</th>${headerCells}<th>Other DPIs</th><th>Referenced</th></tr>
        </thead>
        <tbody>${rows}</tbody>
      </table>
    </div>`;
}

function toggleMatrixRows(btn){
  const section=btn.closest(".section");
  const table=section?section.querySelector(".abi-table"):null;
  if(!table){return;}
  const totalRows=Number(btn.dataset.totalRows||0);
  const visibleLimit=Number(btn.dataset.visibleLimit||5);
  const hint=section?section.querySelector(".abi-row-hint"):null;
  const isCollapsed=table.classList.toggle("abi-table-collapsed");
  btn.textContent=isCollapsed?"Expand":"Collapse";
  if(hint){
    hint.textContent=isCollapsed
      ? `Showing first ${visibleLimit} of ${totalRows} rows`
      : `Showing all ${totalRows} rows`;
  }
}

function toggleAbiMatrixRows(btn){
  toggleMatrixRows(btn);
}

function toggleDpiMatrixRows(btn){
  toggleMatrixRows(btn);
}

function renderResourceStringMatrix(){
  const a=D.apk_info||{};
  const stringDirs=a.string_dirs||{};
  const resources=Object.keys(stringDirs).sort();
  const visibleLimit=5;
  const sec=document.getElementById("resource-string-section");
  const conclusion=a.string_support||"unknown";
  if(!resources.length){
    sec.innerHTML=`<div class="section-header"><h2>&#127760; String Resource Language Matrix</h2></div>
      <div class="abi-conclusion">Conclusion: <strong>${escapeHTML(conclusion)}</strong></div>
      <div class="perm-list"><span class="perm-tag">No string resources found</span></div>`;
    return;
  }
  const allLocales=a.string_locales||[];
  const commonLocales=["default","en","zh","zh-CN","zh-TW","ja","ko","de","fr","es","pt","pt-BR","ru","ar"];
  const displayedLocales=commonLocales.filter(l=>allLocales.includes(l));
  const rows=resources.map(res=>{
    const locales=stringDirs[res]||[];
    const cells=displayedLocales.map(loc=>{
      const has=locales.includes(loc);
      return `<td class="${has?"abi-yes":"abi-no"}">${has?"✅":"❌"}</td>`;
    }).join("");
    const otherForRow=locales.filter(l=>!displayedLocales.includes(l));
    const otherCell=otherForRow.length?`<td class="abi-other">${escapeHTML(otherForRow.join(", "))}</td>`:`<td class="abi-other">-</td>`;
    return `<tr>
      <td>${escapeHTML(res)}</td>
      ${cells}
      ${otherCell}
    </tr>`;
  }).join("");
  const hasMoreRows=resources.length>visibleLimit;
  const actions=hasMoreRows
    ? `<div class="abi-actions">
        <span class="abi-row-hint">Showing first ${visibleLimit} of ${resources.length} rows</span>
        <button class="abi-toggle-btn" data-total-rows="${resources.length}" data-visible-limit="${visibleLimit}" onclick="toggleStringMatrixRows(this)">Expand</button>
      </div>`
    : "";
  const headerCells=displayedLocales.map(l=>`<th>${escapeHTML(l)}</th>`).join("");
  sec.innerHTML=`<div class="section-header"><h2>&#127760; String Resource Language Matrix</h2></div>
    <div class="abi-conclusion">Conclusion: <strong>${escapeHTML(conclusion)}</strong></div>
    ${actions}
    <div class="abi-matrix-wrap">
      <table class="abi-table${hasMoreRows?" abi-table-collapsed":""}">
        <thead>
          <tr><th>String Resource</th>${headerCells}<th>Other Locales</th></tr>
        </thead>
        <tbody>${rows}</tbody>
      </table>
    </div>`;
}

function toggleStringMatrixRows(btn){
  toggleMatrixRows(btn);
}

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("#sdk-sections .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||{};
      // Exclude matched_natives and matched_manifest_services from allPkgs: they are already shown via matched_rules (native_libs:xxx, manifest_services:xxx)
      const allPkgs=[...(ev.matched_packages||[])];
      const matchedRules=ev.matched_rules||[];
      const pkgTags=allPkgs.slice(0,3).map(p=>`<span>${escapeHTML(p)}</span>`).join("");
      const ruleTags=matchedRules.slice(0,3).map(rule=>`<span class="${ruleClass(rule)}" title="${escapeHTML(ruleTooltip(rule))}">${escapeHTML(ruleDisplayText(rule))}</span>`).join("");
      const moreRules=matchedRules.length>3?`<span class="rule-other">+${matchedRules.length-3}</span>`:"";
      const evidenceParts=[];
      if(allPkgs.length)evidenceParts.push(pkgTags);
      if(matchedRules.length)evidenceParts.push(ruleTags+moreRules);
      const evidenceBlock=evidenceParts.length?`<div class="evidence">${evidenceParts.join("")}</div>`:"";
      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,...(ev.matched_natives||[]),...matchedRules].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>
          ${evidenceBlock}
        </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(); renderNativeAbiMatrix(); renderResourceDpiMatrix(); renderResourceStringMatrix(); 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)
        string_section = _render_string_section_html(self.result)
        html = html.replace("__STRING_SECTION_HTML__", string_section)
        with open(path, "w", encoding="utf-8") as f:
            f.write(html)
