import base64
import html
import io
import qrcode

from apps.document_engine.services.localization_helpers import (
    amount_to_words,
    bilingual_label,
    format_currency,
    format_dates,
    to_nepali_digits,
)

PAPER_CSS_MAP = {
    "A4": "A4",
    "A5": "A5",
    "A3": "A3",
    "LETTER": "letter",
    "LEGAL": "legal",
    "THERMAL_80": "80mm 220mm",
    "THERMAL_58": "58mm 200mm",
}


def generate_qr_data_uri(payload: str) -> str:
    qr = qrcode.QRCode(version=1, box_size=4, border=1)
    qr.add_data(payload)
    qr.make(fit=True)
    img = qr.make_image(fill_color="#0f172a", back_color="#ffffff")
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    b64 = base64.b64encode(buf.getvalue()).decode("ascii")
    return f"data:image/png;base64,{b64}"


def generate_barcode_svg(code_text: str) -> str:
    """Clean deterministic inline Code39-inspired vector bars without external assets."""
    clean = html.escape(code_text or "MAYA-OS")
    bars = []
    x = 4
    for ch in clean[:28]:
        bits = format(ord(ch) % 64, "06b")
        for b in bits:
            w = 2 if b == "1" else 1
            if b == "1":
                bars.append(f'<rect x="{x}" y="2" width="{w}" height="26" fill="#0f172a" />')
            x += w + 1
        x += 2
    width = max(120, x + 4)
    return (
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="38" viewBox="0 0 {width} 38">'
        + "".join(bars)
        + f'<text x="{width // 2}" y="36" font-size="8" text-anchor="middle" fill="#334155">{clean}</text></svg>'
    )


def _css_page_size(cfg: dict) -> str:
    paper = cfg.get("paper_size", "A4")
    orient = "landscape" if cfg.get("orientation") == "LANDSCAPE" else "portrait"
    if paper == "CUSTOM":
        return f"{cfg.get('custom_width_mm', 210)}mm {cfg.get('custom_height_mm', 297)}mm {orient}"
    base = PAPER_CSS_MAP.get(paper, "A4")
    if paper.startswith("THERMAL"):
        return base
    return f"{base} {orient}"


def render_document_html(
    *,
    payload: dict,
    resolved: dict,
    verification_code: str = "",
    version_no: int = 1,
    appendices: list[dict] | None = None,
) -> str:
    """Render controlled layout AST + verified data payload into HTML5/CSS Print markup."""
    cfg = resolved["print_profile"]
    settings = resolved["settings"]
    layout = resolved["layout_schema"]
    signatures = resolved["signatures"]
    lang = cfg.get("language", "BILINGUAL")
    ne_digits = lang == "NE"
    cur = payload.get("currency") or settings.get("currency_symbol") or "NPR"
    dates = format_dates(
        payload.get("issue_date"),
        cfg.get("date_format", "BOTH"),
        language=lang,
        digit_style="NE" if ne_digits else "EN",
    )

    accent = html.escape(str(cfg.get("accent_color") or "#0f766e"))
    font_family = html.escape(str(cfg.get("font_family") or "Noto Sans Devanagari, Inter, sans-serif"))
    is_thermal = str(cfg.get("paper_size", "")).startswith("THERMAL")
    table_style = cfg.get("table_style", "STANDARD")
    cell_pad = "3px 5px" if table_style == "COMPACT" or is_thermal else ("8px 9px" if table_style == "DETAILED" else "5px 7px")
    font_sz = "9px" if is_thermal else ("10px" if table_style == "COMPACT" else "11px")
    grayscale = "filter: grayscale(100%);" if cfg.get("color_mode") == "GRAYSCALE" else ""
    border_css = "border: 1px solid #cbd5e1;" if cfg.get("show_border", True) and not is_thermal else ""

    watermark = ""
    if cfg.get("watermark_mode") == "CUSTOM" and cfg.get("watermark_text"):
        watermark = cfg["watermark_text"]
    elif cfg.get("watermark_mode", "AUTO_STATUS") == "AUTO_STATUS":
        st = str(payload.get("status", "")).upper()
        if st in ("DRAFT", "CANCELLED", "VOID", "PAID", "APPROVED"):
            watermark = st

    page_counter_css = ""
    if cfg.get("show_footer", True) and (cfg.get("show_page_number", True) or cfg.get("show_page_count", True)):
        if cfg.get("show_page_number") and cfg.get("show_page_count"):
            page_counter_css = '@bottom-right { content: "Page " counter(page) " of " counter(pages); font-size: 9px; color: #64748b; }'
        elif cfg.get("show_page_number"):
            page_counter_css = '@bottom-right { content: "Page " counter(page); font-size: 9px; color: #64748b; }'

    footer_left = (
        f'@bottom-left {{ content: "v{version_no} · {html.escape(payload.get("document_number", ""))} · Maya OS"; font-size: 9px; color: #64748b; }}'
        if cfg.get("show_footer", True)
        else ""
    )

    page_size = _css_page_size(cfg)
    margins = f"{cfg.get('margin_top_mm', 12)}mm {cfg.get('margin_right_mm', 12)}mm {cfg.get('margin_bottom_mm', 14)}mm {cfg.get('margin_left_mm', 12)}mm"

    qr_img_tag = ""
    if cfg.get("show_qr_code", True):
        qr_payload = f"MAYA|{settings.get('legal_name')}|{payload.get('document_type')}|{payload.get('document_number')}|{verification_code or 'PREVIEW'}"
        qr_img_tag = f'<img src="{generate_qr_data_uri(qr_payload)}" alt="QR" style="width:68px;height:68px;border:1px solid #e2e8f0;padding:2px;" />'

    barcode_svg = generate_barcode_svg(payload.get("document_number") or verification_code) if cfg.get("show_barcode") else ""

    sections_html = []
    for sec in layout.get("sections", []):
        if not sec.get("visible", True):
            continue
        stype = sec.get("type")

        if stype == "header" and cfg.get("show_header", True):
            logo_html = (
                f'<img src="{html.escape(cfg["logo_data_uri"])}" alt="Logo" style="max-height:48px;max-width:120px;object-fit:contain;" />'
                if cfg.get("show_logo", True) and cfg.get("logo_data_uri")
                else f'<div style="width:44px;height:44px;border-radius:8px;background:{accent};color:#fff;font-weight:700;display:flex;align-items:center;justify-content:center;font-size:15px;">{html.escape((settings.get("legal_name") or "MO")[:2].upper())}</div>'
            )
            title_txt = html.escape(payload.get("title") or "Document")
            if lang == "NE" and payload.get("title_ne"):
                title_txt = html.escape(payload["title_ne"])
            elif lang == "BILINGUAL" and payload.get("title_ne"):
                title_txt = f"{html.escape(payload['title'])} · {html.escape(payload['title_ne'])}"

            copy_badge = html.escape(str(cfg.get("copy_type") or "ORIGINAL"))
            sections_html.append(
                f"""
                <div class="doc-header" style="display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid {accent};padding-bottom:8px;margin-bottom:10px;gap:12px;">
                  <div style="display:flex;gap:10px;align-items:center;">
                    {logo_html}
                    <div>
                      <div style="font-size:15px;font-weight:800;color:#0f172a;">{html.escape(str(settings.get("legal_name") or ""))}</div>
                      <div style="font-size:10px;color:#475569;">{html.escape(str(settings.get("company_address") or ""))}</div>
                      <div style="font-size:10px;color:#475569;">PAN/VAT: <strong>{html.escape(str(settings.get("pan_vat_no") or "-"))}</strong> · Reg: {html.escape(str(settings.get("registration_no") or "-"))}</div>
                    </div>
                  </div>
                  <div style="text-align:right;">
                    <div style="font-size:14px;font-weight:800;color:{accent};">{title_txt}</div>
                    <span style="display:inline-block;margin-top:4px;padding:2px 8px;border:1px solid {accent};border-radius:999px;font-size:9px;font-weight:700;color:{accent};">{copy_badge}</span>
                  </div>
                </div>
                """
            )

        elif stype == "meta_grid":
            meta_items = [
                (bilingual_label("Document No", "कागजात नं.", lang), payload.get("document_number") or "-"),
                (bilingual_label("Date", "मिति", lang), dates["display"] or "-"),
                (bilingual_label("Status", "स्थिति", lang), payload.get("status") or "-"),
                (bilingual_label("Currency", "मुद्रा", lang), cur),
            ]
            for m in payload.get("metadata", []):
                meta_items.append((m.get("label", ""), m.get("value", "")))
            cells = "".join(
                f'<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:4px;padding:4px 7px;"><div style="font-size:8px;text-transform:uppercase;color:#64748b;font-weight:700;">{html.escape(str(k))}</div><div style="font-size:10px;font-weight:700;color:#0f172a;">{html.escape(str(v))}</div></div>'
                for k, v in meta_items[:8]
            )
            sections_html.append(
                f'<div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin-bottom:10px;">{cells}</div>'
            )

        elif stype == "party_info":
            party = payload.get("party") or {}
            proj = payload.get("project") or {}
            sections_html.append(
                f"""
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px;">
                  <div style="border:1px solid #e2e8f0;border-radius:5px;padding:7px 9px;">
                    <div style="font-size:9px;font-weight:700;color:{accent};text-transform:uppercase;margin-bottom:3px;">{html.escape(bilingual_label("Party / Recipient", "ग्राहक / पक्ष", lang))}</div>
                    <div style="font-weight:700;font-size:11px;">{html.escape(str(party.get("name") or "-"))}</div>
                    <div style="font-size:10px;color:#475569;">PAN/VAT: {html.escape(str(party.get("pan_vat") or "-"))}</div>
                    <div style="font-size:10px;color:#475569;">{html.escape(str(party.get("address") or ""))}</div>
                  </div>
                  <div style="border:1px solid #e2e8f0;border-radius:5px;padding:7px 9px;">
                    <div style="font-size:9px;font-weight:700;color:{accent};text-transform:uppercase;margin-bottom:3px;">{html.escape(bilingual_label("Project & Site Dimension", "परियोजना र साइट", lang))}</div>
                    <div style="font-weight:700;font-size:11px;">{html.escape(str(proj.get("code") or "-"))} · {html.escape(str(proj.get("name") or "-"))}</div>
                    <div style="font-size:10px;color:#475569;">Site: {html.escape(str(proj.get("site") or "-"))}</div>
                  </div>
                </div>
                """
            )

        elif stype == "line_items":
            cols = payload.get("columns") or sec.get("columns") or []
            visible_cols = [c for c in cols if c.get("visible", True)]
            ths = "".join(
                f'<th style="padding:{cell_pad};text-align:{c.get("align", "left")};background:{accent};color:#ffffff;font-size:9px;text-transform:uppercase;border:1px solid {accent};">{html.escape(str(c.get("label", c.get("key", ""))))}</th>'
                for c in visible_cols
            )
            trs = []
            for row in payload.get("rows", []):
                tds = []
                for c in visible_cols:
                    key = c["key"]
                    val = row.get(key, "")
                    ctype = c.get("type", "text")
                    if ctype == "money":
                        disp = format_currency(val, cur, ne_digits=ne_digits)
                    elif ne_digits and ctype in ("int", "number", "date"):
                        disp = to_nepali_digits(str(val))
                    else:
                        disp = str(val)
                    tds.append(
                        f'<td style="padding:{cell_pad};text-align:{c.get("align", "left")};border-bottom:1px solid #e2e8f0;border-left:1px solid #e2e8f0;border-right:1px solid #e2e8f0;height:{cfg.get("row_height_px", 24)}px;">{html.escape(disp)}</td>'
                    )
                trs.append(f'<tr style="break-inside:avoid;page-break-inside:avoid;">{"".join(tds)}</tr>')
            if not trs:
                trs.append(f'<tr><td colspan="{max(1, len(visible_cols))}" style="padding:10px;text-align:center;color:#64748b;">No line items recorded.</td></tr>')
            sections_html.append(
                f"""
                <table style="width:100%;border-collapse:collapse;margin-bottom:10px;font-size:{font_sz};">
                  <thead style="display:table-header-group;"><tr>{ths}</tr></thead>
                  <tbody>{"".join(trs)}</tbody>
                </table>
                """
            )

        elif stype == "totals":
            totals = payload.get("totals") or {}
            sections_html.append(
                f"""
                <div class="no-break" style="display:flex;justify-content:flex-end;margin-bottom:8px;">
                  <table style="width:280px;border-collapse:collapse;font-size:10px;">
                    <tr>
                      <td style="padding:4px 8px;border:1px solid #e2e8f0;color:#475569;">{html.escape(bilingual_label("Subtotal", "जम्मा", lang))}</td>
                      <td style="padding:4px 8px;border:1px solid #e2e8f0;text-align:right;font-weight:600;">{html.escape(format_currency(totals.get("subtotal", 0), cur, ne_digits))}</td>
                    </tr>
                    <tr>
                      <td style="padding:4px 8px;border:1px solid #e2e8f0;color:#475569;">{html.escape(str(totals.get("tax_label") or "VAT / Tax"))}</td>
                      <td style="padding:4px 8px;border:1px solid #e2e8f0;text-align:right;font-weight:600;">{html.escape(format_currency(totals.get("tax_amount", 0), cur, ne_digits))}</td>
                    </tr>
                    <tr style="background:#f1f5f9;">
                      <td style="padding:6px 8px;border:1px solid #cbd5e1;font-weight:800;color:#0f172a;">{html.escape(bilingual_label("Grand Total", "कुल जम्मा", lang))}</td>
                      <td style="padding:6px 8px;border:1px solid #cbd5e1;text-align:right;font-weight:800;color:{accent};font-size:11px;">{html.escape(format_currency(totals.get("grand_total", 0), cur, ne_digits))}</td>
                    </tr>
                  </table>
                </div>
                """
            )

        elif stype == "amount_words":
            grand = (payload.get("totals") or {}).get("grand_total", 0)
            words = amount_to_words(grand, cur, "NE" if lang == "NE" else "EN")
            sections_html.append(
                f'<div class="no-break" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:4px;padding:6px 9px;margin-bottom:8px;font-size:10px;"><strong>{html.escape(bilingual_label("Amount in Words", "अक्षरेपी रकम", lang))}:</strong> {html.escape(words)}</div>'
            )

        elif stype == "notes":
            narr = payload.get("narration") or ""
            terms = payload.get("terms") or []
            if narr or terms:
                terms_html = "".join(f"<div>{html.escape(str(t))}</div>" for t in terms)
                sections_html.append(
                    f'<div class="no-break" style="margin-bottom:10px;font-size:10px;color:#334155;">'
                    + (f"<div><strong>Remarks:</strong> {html.escape(str(narr))}</div>" if narr else "")
                    + terms_html
                    + "</div>"
                )

        elif stype == "qr_barcode" and (qr_img_tag or barcode_svg):
            sections_html.append(
                f"""
                <div class="no-break" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;padding:6px 8px;border:1px dashed #cbd5e1;border-radius:5px;">
                  <div>
                    <div style="font-size:9px;font-weight:700;color:#0f172a;">Document Verification</div>
                    <div style="font-size:9px;color:#475569;">Code: {html.escape(verification_code or "PREVIEW")} · Version v{version_no}</div>
                    {barcode_svg}
                  </div>
                  {qr_img_tag}
                </div>
                """
            )

        elif stype == "signatures":
            cols_sig = "".join(
                f'<div style="text-align:center;padding-top:26px;border-top:1px solid #64748b;font-size:9px;font-weight:700;color:#334155;">{html.escape(str(slot.get("label") or slot.get("role") or "Authorized"))}</div>'
                for slot in signatures
            )
            stamp_img = (
                f'<div style="text-align:center;"><img src="{html.escape(resolved["stamp_data_uri"])}" alt="Stamp" style="max-height:56px;" /></div>'
                if resolved.get("stamp_data_uri")
                else ""
            )
            sections_html.append(
                f'<div class="no-break" style="display:grid;grid-template-columns:repeat({max(1, len(signatures) + (1 if stamp_img else 0))},1fr);gap:18px;margin-top:18px;align-items:end;">{cols_sig}{stamp_img}</div>'
            )

    if appendices:
        app_rows = "".join(
            f"<li>{html.escape(a.get('title', 'Attachment'))} ({html.escape(a.get('file_name', ''))})</li>"
            for a in appendices
        )
        sections_html.append(
            f'<div style="page-break-before:always;margin-top:14px;"><h3 style="color:{accent};font-size:12px;">Supporting Attachments Appendix</h3><ul>{app_rows}</ul></div>'
        )

    watermark_html = (
        f'<div style="position:fixed;top:42%;left:18%;transform:rotate(-32deg);font-size:58px;font-weight:800;color:rgba(148,163,184,0.18);letter-spacing:8px;pointer-events:none;z-index:0;">{html.escape(watermark)}</div>'
        if watermark
        else ""
    )

    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>{html.escape(payload.get("title", "Maya OS Document"))}</title>
  <style>
    @page {{
      size: {page_size};
      margin: {margins};
      {footer_left}
      {page_counter_css}
    }}
    body {{
      font-family: {font_family};
      font-size: {font_sz};
      color: #0f172a;
      margin: 0;
      padding: 0;
      {grayscale}
    }}
    .sheet {{
      position: relative;
      padding: 10px 12px;
      {border_css}
      border-radius: 4px;
    }}
    .no-break {{
      break-inside: avoid;
      page-break-inside: avoid;
    }}
  </style>
</head>
<body>
  {watermark_html}
  <div class="sheet">
    {"".join(sections_html)}
  </div>
</body>
</html>"""

