"""HTML report templates for compliance reports."""
from __future__ import annotations

def get_html_template(result) -> str:
    from .compliance_reports import ReportType
    templates = {
        ReportType.MONTHLY_SPENDING: _monthly_spending_html,
        ReportType.POLICY_COMPLIANCE: _policy_compliance_html,
        ReportType.KYA_VERIFICATION: _kya_verification_html,
        ReportType.AUDIT_TRAIL: _audit_trail_html,
        ReportType.TAX_REPORT: _tax_report_html,
    }
    return templates.get(result.report_type, _default_html)(result)

_CSS = """
<style>
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; margin: 0; padding: 20px; background: #f8f9fa; color: #1a1a2e; }
  .header { background: linear-gradient(135deg, #7C3AED, #4C1D95); color: white; padding: 30px; border-radius: 12px; margin-bottom: 24px; }
  .header h1 { margin: 0 0 8px 0; font-size: 24px; }
  .header p { margin: 0; opacity: 0.85; }
  .card { background: white; border-radius: 8px; padding: 20px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
  .card h2 { margin: 0 0 16px 0; font-size: 18px; color: #4C1D95; }
  table { width: 100%; border-collapse: collapse; }
  th { background: #f3f4f6; text-align: left; padding: 10px 12px; font-size: 13px; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; }
  td { padding: 10px 12px; border-bottom: 1px solid #f3f4f6; }
  .badge { display: inline-block; padding: 2px 8px; border-radius: 9999px; font-size: 12px; font-weight: 500; }
  .badge-green { background: #d1fae5; color: #065f46; }
  .badge-red { background: #fee2e2; color: #991b1b; }
  .badge-amber { background: #fef3c7; color: #92400e; }
  .stat { text-align: center; }
  .stat-value { font-size: 28px; font-weight: 700; color: #4C1D95; }
  .stat-label { font-size: 13px; color: #6b7280; margin-top: 4px; }
  .stats-row { display: flex; gap: 16px; margin-bottom: 16px; }
  .stats-row .card { flex: 1; }
  .footer { text-align: center; color: #9ca3af; font-size: 12px; margin-top: 24px; padding: 16px; }
  @media print { body { background: white; } .card { box-shadow: none; border: 1px solid #e5e7eb; } }
</style>
"""

def _monthly_spending_html(result) -> str:
    s = result.summary
    d = result.data
    agents_rows = ""
    for a in d.get("agent_breakdown", []):
        agents_rows += f"<tr><td>{a['agent_id']}</td><td>${a['total']}</td><td>{a['tx_count']}</td><td>${a['avg_tx']}</td><td>{a['top_merchant']}</td></tr>"
    merchants_rows = ""
    for m in d.get("top_merchants", []):
        merchants_rows += f"<tr><td>{m['merchant']}</td><td>${m['total']}</td><td>{m['category']}</td></tr>"
    return f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>Monthly Spending Report</title>{_CSS}</head><body>
<div class="header"><h1>Monthly Spending Report</h1><p>{d.get('period',{}).get('from','')} to {d.get('period',{}).get('to','')}</p></div>
<div class="stats-row"><div class="card stat"><div class="stat-value">${s.get('total_spend','0')}</div><div class="stat-label">Total Spend</div></div>
<div class="card stat"><div class="stat-value">{s.get('active_agents',0)}</div><div class="stat-label">Active Agents</div></div>
<div class="card stat"><div class="stat-value">{s.get('total_transactions',0)}</div><div class="stat-label">Transactions</div></div>
<div class="card stat"><div class="stat-value">{s.get('month_over_month_change','')}</div><div class="stat-label">MoM Change</div></div></div>
<div class="card"><h2>Agent Breakdown</h2><table><thead><tr><th>Agent</th><th>Total</th><th>Tx Count</th><th>Avg Tx</th><th>Top Merchant</th></tr></thead><tbody>{agents_rows}</tbody></table></div>
<div class="card"><h2>Top Merchants</h2><table><thead><tr><th>Merchant</th><th>Total</th><th>Category</th></tr></thead><tbody>{merchants_rows}</tbody></table></div>
<div class="footer">Generated by Sardis Compliance Engine | {result.generated_at.strftime('%Y-%m-%d %H:%M UTC')}</div></body></html>"""

def _policy_compliance_html(result) -> str:
    s = result.summary
    d = result.data
    violations_rows = ""
    for v in d.get("violations", []):
        violations_rows += f"<tr><td>{v['date']}</td><td>{v['agent']}</td><td>${v['amount']}</td><td>{v['reason']}</td><td><span class='badge badge-red'>{v['policy']}</span></td></tr>"
    return f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>Policy Compliance Report</title>{_CSS}</head><body>
<div class="header"><h1>Policy Compliance Report</h1><p>{d.get('period',{}).get('from','')} to {d.get('period',{}).get('to','')}</p></div>
<div class="stats-row"><div class="card stat"><div class="stat-value">{s.get('compliance_rate','')}</div><div class="stat-label">Compliance Rate</div></div>
<div class="card stat"><div class="stat-value">{d.get('approved',0)}</div><div class="stat-label">Approved</div></div>
<div class="card stat"><div class="stat-value">{s.get('total_blocks',0)}</div><div class="stat-label">Blocked</div></div></div>
<div class="card"><h2>Policy Violations</h2><table><thead><tr><th>Date</th><th>Agent</th><th>Amount</th><th>Reason</th><th>Policy</th></tr></thead><tbody>{violations_rows}</tbody></table></div>
<div class="footer">Generated by Sardis Compliance Engine | {result.generated_at.strftime('%Y-%m-%d %H:%M UTC')}</div></body></html>"""

def _kya_verification_html(result) -> str:
    d = result.data
    agents_rows = ""
    for a in d.get("agents", []):
        badge = "badge-green" if a['status'] == 'verified' else "badge-red"
        agents_rows += f"<tr><td>{a['agent_id']}</td><td>Level {a['kya_level']}</td><td><span class='badge {badge}'>{a['status']}</span></td><td>{a['owner']}</td><td>{a['expires_at']}</td></tr>"
    return f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>KYA Verification Report</title>{_CSS}</head><body>
<div class="header"><h1>KYA Verification Report</h1><p>Know Your Agent - Verification Status</p></div>
<div class="card"><h2>Agent Verification Status</h2><table><thead><tr><th>Agent</th><th>KYA Level</th><th>Status</th><th>Owner</th><th>Expires</th></tr></thead><tbody>{agents_rows}</tbody></table></div>
<div class="footer">Generated by Sardis Compliance Engine | {result.generated_at.strftime('%Y-%m-%d %H:%M UTC')}</div></body></html>"""

def _audit_trail_html(result) -> str:
    d = result.data
    entries_rows = ""
    for e in d.get("entries", []):
        entries_rows += f"<tr><td>{e['index']}</td><td>{e['action']}</td><td>{e['agent_id']}</td><td>${e['amount']}</td><td><code>{e['entry_hash'][:16]}...</code></td></tr>"
    valid = "<span class='badge badge-green'>Valid</span>" if d.get("chain_valid") else "<span class='badge badge-red'>Invalid</span>"
    return f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>Audit Trail Report</title>{_CSS}</head><body>
<div class="header"><h1>Audit Trail Report</h1><p>Tamper-Evident Ledger | Chain Integrity: {valid}</p></div>
<div class="card"><h2>Ledger Entries</h2><table><thead><tr><th>#</th><th>Action</th><th>Agent</th><th>Amount</th><th>Hash</th></tr></thead><tbody>{entries_rows}</tbody></table></div>
<div class="footer">Generated by Sardis Compliance Engine | {result.generated_at.strftime('%Y-%m-%d %H:%M UTC')}</div></body></html>"""

def _tax_report_html(result) -> str:
    s = result.summary
    d = result.data
    cat_rows = ""
    for c in d.get("categories", []):
        ded = "<span class='badge badge-green'>Yes</span>" if c['deductible'] else "<span class='badge badge-red'>No</span>"
        cat_rows += f"<tr><td>{c['category']}</td><td>${c['total']}</td><td>{ded}</td><td>{c['tax_code']}</td></tr>"
    return f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>Tax Report</title>{_CSS}</head><body>
<div class="header"><h1>Tax Report</h1><p>{d.get('period',{}).get('from','')} to {d.get('period',{}).get('to','')}</p></div>
<div class="stats-row"><div class="card stat"><div class="stat-value">${s.get('total_spend','0')}</div><div class="stat-label">Total</div></div>
<div class="card stat"><div class="stat-value">${s.get('deductible','0')}</div><div class="stat-label">Deductible</div></div>
<div class="card stat"><div class="stat-value">{s.get('deductible_rate','')}</div><div class="stat-label">Deductible Rate</div></div></div>
<div class="card"><h2>Spending by Category</h2><table><thead><tr><th>Category</th><th>Total</th><th>Deductible</th><th>Tax Code</th></tr></thead><tbody>{cat_rows}</tbody></table></div>
<div class="footer">Generated by Sardis Compliance Engine | {result.generated_at.strftime('%Y-%m-%d %H:%M UTC')}</div></body></html>"""

def _default_html(result) -> str:
    import json
    return f"""<!DOCTYPE html><html><head><meta charset="utf-8"><title>Report</title>{_CSS}</head><body>
<div class="header"><h1>{result.report_type.value}</h1></div>
<div class="card"><pre>{json.dumps(result.data, indent=2)}</pre></div></body></html>"""
