from __future__ import annotations

import html
from pathlib import Path
from typing import Any


REVIEW_WARNING = (
    "Physician review required before signing in the EMR. Verify actual medications, "
    "doses, lot/expiry, devices, image documentation, response, complications, and follow-up."
)


def form_filename(form: dict[str, Any], suffix: str) -> str:
    return f"{form['form_id']}.{suffix}"


def render_static_html(form: dict[str, Any]) -> str:
    title = html.escape(str(form.get("title", "")))
    form_id = html.escape(str(form.get("form_id", "")))
    form_type = html.escape(str(form.get("form_type", "")))
    family = html.escape(str(form.get("family", "")))
    rows = "\n".join(_html_field_row(field) for field in form.get("fields", []))
    template = html.escape(str(form.get("narrative_template") or form.get("template") or "")).replace(
        "\n", "<br>"
    )

    return (
        "<!doctype html>\n"
        "<html>\n"
        "<head>\n"
        "  <meta charset=\"utf-8\">\n"
        f"  <title>{title}</title>\n"
        "  <style>\n"
        "    body{font-family:Arial,sans-serif;line-height:1.45;color:#1a202c;max-width:1100px;margin:24px auto;padding:0 16px;}\n"
        "    table{border-collapse:collapse;width:100%;}\n"
        "    td,th{border:1px solid #ccc;padding:6px;font-size:12px;vertical-align:top;}\n"
        "    th{background:#0f766e;color:white;text-align:left;}\n"
        "    code{font-size:11px;}\n"
        "    .note{white-space:normal;background:#f8fafc;border:1px solid #ddd;padding:12px;}\n"
        "  </style>\n"
        "</head>\n"
        "<body>\n"
        f"  <h1>{title}</h1>\n"
        f"  <p><b>Form ID:</b> {form_id} &nbsp; <b>Type:</b> {form_type} &nbsp; <b>Family:</b> {family}</p>\n"
        "  <h2>Structured fields</h2>\n"
        "  <table>\n"
        "    <tr><th>Section</th><th>Field</th><th>Key</th><th>Default layer</th><th>Required</th><th>Quick text templates</th><th>History/exam sources</th></tr>\n"
        f"{rows}\n"
        "  </table>\n"
        "  <h2>Narrative template</h2>\n"
        f"  <div class=\"note\">{template}</div>\n"
        f"  <p>{html.escape(REVIEW_WARNING)}</p>\n"
        "</body>\n"
        "</html>\n"
    )


def _html_field_row(field: dict[str, Any]) -> str:
    required = "Required" if field.get("required") else "Optional"
    return (
        "    <tr>"
        f"<td>{html.escape(str(field.get('section', '')))}</td>"
        f"<td>{html.escape(str(field.get('label', '')))}</td>"
        f"<td><code>{html.escape(str(field.get('key', '')))}</code></td>"
        f"<td>{html.escape(str(field.get('default_layer', '')))}</td>"
        f"<td>{required}</td>"
        f"<td>{html.escape(_join_list(field.get('quick_options', '')))}</td>"
        f"<td>{html.escape(_join_list(field.get('context_sources', '')))}</td>"
        "</tr>"
    )


def render_static_rtf(form: dict[str, Any]) -> str:
    lines = [
        str(form.get("title", "")),
        "",
        f"Form ID: {form.get('form_id', '')}",
        f"Type: {form.get('form_type', '')}",
        f"Family: {form.get('family', '')}",
        "",
        "Structured fields:",
    ]
    for field in form.get("fields", []):
        required = "Required" if field.get("required") else "Optional"
        lines.append(
            " - "
            + " | ".join(
                [
                    str(field.get("section", "")),
                    str(field.get("label", "")),
                    str(field.get("key", "")),
                    str(field.get("default_layer", "")),
                    required,
                    "Quick text: " + _join_list(field.get("quick_options", "")),
                    "Hx/Exam sources: " + _join_list(field.get("context_sources", "")),
                ]
            )
        )

    lines.extend(
        [
            "",
            "Narrative template:",
            str(form.get("narrative_template") or form.get("template") or ""),
            "",
            REVIEW_WARNING,
        ]
    )
    body = "\\par\n".join(_rtf_escape(line) for line in "\n".join(lines).splitlines())
    return "{\\rtf1\\ansi\\deff0{\\fonttbl{\\f0 Arial;}}\\fs20 " + body + "}"


def _rtf_escape(value: str) -> str:
    escaped: list[str] = []
    for char in value:
        codepoint = ord(char)
        if char in {"\\", "{", "}"}:
            escaped.append("\\" + char)
        elif char == "\t":
            escaped.append("\\tab ")
        elif codepoint > 127:
            signed = codepoint if codepoint < 32768 else codepoint - 65536
            escaped.append(f"\\u{signed}?")
        else:
            escaped.append(char)
    return "".join(escaped)


def _join_list(value: Any) -> str:
    if isinstance(value, list):
        return "; ".join(str(item) for item in value if str(item).strip())
    return str(value or "")


def write_static_form_outputs(data: dict[str, Any], output_dir: Path) -> dict[str, str]:
    html_dir = output_dir / "Form_HTML"
    rtf_dir = output_dir / "Form_RTF"
    html_dir.mkdir(parents=True, exist_ok=True)
    rtf_dir.mkdir(parents=True, exist_ok=True)

    for stale_file in [*html_dir.glob("*.html"), *rtf_dir.glob("*.rtf")]:
        stale_file.unlink()

    for form in data.get("forms", []):
        (html_dir / form_filename(form, "html")).write_text(render_static_html(form), encoding="utf-8")
        (rtf_dir / form_filename(form, "rtf")).write_text(render_static_rtf(form), encoding="utf-8")

    return {
        "form_html": str(html_dir),
        "form_rtf": str(rtf_dir),
    }
