"""Build the offline architecture walkthrough; this is a documentation renderer."""
from pathlib import Path
import json
from build_case_traces import build
from build_operations_examples import build_preview
from build_agent_map import build as build_agent_map
from build_case_content_docs import update_catalogues, update_studies, update_marketing_content

HERE = Path(__file__).resolve().parent
data = json.loads((HERE / "case-journeys.json").read_text(encoding="utf-8"))
template = (HERE / "case_journeys.template.html").read_text(encoding="utf-8")
template = template.replace('@@CHAT_JS@@',(HERE/'case_chat.js').read_text(encoding='utf-8')).replace('@@CHAT_CSS@@',(HERE/'case_chat.css').read_text(encoding='utf-8'))

GROUPS = [("DC", "Data & Manipulation"), ("CF", "Configuration"), ("DV", "Development")]


def index_html(cases):
    """A static list of every case: the anchor each catalogue deep-links to, and the
    walkthrough's contents when scripting is unavailable."""
    esc = lambda s: s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
    out = []
    for prefix, label in GROUPS:
        rows = [c for c in cases if c["id"].startswith(prefix)]
        links = "".join(
            '<a href="#{0}">{0} · {1}</a>'.format(c["id"], esc(c["title"])) for c in rows
        )
        out.append(
            '<div class="ci-group"><b>{0} · {1}</b><div class="ci-list">{2}</div></div>'.format(
                label, len(rows), links
            )
        )
    return "".join(out)


def options_html(cases):
    """The case picker, rendered statically: each option id is the case's permanent link target.
    The script replaces these options on load, so a deep link resolves without scrolling the
    reader away from the journey."""
    esc = lambda s: s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
    return "".join(
        '<option id="{0}" value="{0}">{0} · {1}</option>'.format(c["id"], esc(c["title"])) for c in cases
    )


encoded = json.dumps(data, ensure_ascii=False).replace("<", "\\u003c")
trace_data = build()
traces = json.dumps(trace_data, ensure_ascii=False).replace("<", "\\u003c")
(HERE / "case_journeys.html").write_text(
    template.replace("@@CASES@@", encoded)
            .replace("@@TRACES@@", traces)
            .replace("@@INDEX@@", index_html(data["cases"]))
            .replace("@@OPTIONS@@", options_html(data["cases"])),
    encoding="utf-8",
)
build_preview(template,data,trace_data)
update_catalogues(data['cases'],trace_data)
update_studies(trace_data)
update_marketing_content(trace_data)
build_agent_map()
print(f"Built walkthrough: {len(data['cases'])} cases, module-specific paths, five adaptive screens and stage-bound protocol examples")
