#!/usr/bin/env python3
"""Compile prepared chunks under prepared-docs/HailerPublic/ into a single
TypeScript module that exports the full knowledge corpus as a string.

Run from the repo root:

    python3 scripts/build-public-chat-knowledge.py

Re-run whenever you edit any prepared-docs/HailerPublic/**/*.json file.
"""
import json
import glob
import os
import sys

REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
SOURCE_GLOB = os.path.join(REPO_ROOT, "prepared-docs", "HailerPublic", "**", "*.json")
OUTPUT_TS = os.path.join(REPO_ROOT, "src", "public-chat", "knowledge.ts")

SCOPE_TITLES = {
    "product": "Product & UI",
    "developer": "Developer & MCP",
    "legal": "Legal & Privacy",
}
TOPIC_TITLES = {
    "overview": "Overview",
    "ui-guide": "UI Guide",
    "product-description": "Product Description",
    "faq": "Frequently Asked Questions",
    "mcp-server": "MCP Server",
    "apps-and-marketplace": "Apps & Marketplace",
    "getting-started": "Getting Started",
    "privacy-policy": "Privacy Policy",
}


def main() -> int:
    chunks_by_scope_topic: dict = {}
    for path in sorted(glob.glob(SOURCE_GLOB, recursive=True)):
        with open(path) as f:
            chunks = json.load(f)
        for c in chunks:
            chunks_by_scope_topic.setdefault(c["scope"], {}).setdefault(c["topic"], []).append(c)

    for scope_map in chunks_by_scope_topic.values():
        for topic_chunks in scope_map.values():
            topic_chunks.sort(key=lambda c: c["chunk_index"])

    parts = [
        "# Hailer Knowledge Base",
        "",
        (
            "This is the curated, public-safe knowledge corpus that the public chatbot "
            "uses to answer questions about Hailer. It covers product concepts, the user "
            "interface, the MCP server, app development, and getting started."
        ),
        "",
    ]

    for scope in sorted(chunks_by_scope_topic.keys()):
        parts.append(f"## {SCOPE_TITLES.get(scope, scope)}")
        parts.append("")
        for topic in sorted(chunks_by_scope_topic[scope].keys()):
            parts.append(f"### {TOPIC_TITLES.get(topic, topic)}")
            parts.append("")
            for c in chunks_by_scope_topic[scope][topic]:
                parts.append(f"#### {c['title']}")
                parts.append("")
                parts.append(c["content"])
                parts.append("")

    corpus = "\n".join(parts)

    escaped = corpus.replace("\\", "\\\\").replace("`", "\\`").replace("${", "\\${")
    total_chunks = sum(len(t) for s in chunks_by_scope_topic.values() for t in s.values())
    scopes = ", ".join(sorted(chunks_by_scope_topic.keys()))

    ts = (
        "// AUTO-GENERATED from prepared-docs/HailerPublic/ — do not edit by hand.\n"
        "// Regenerate via: python3 scripts/build-public-chat-knowledge.py\n"
        "//\n"
        f"// Source chunks: {total_chunks}\n"
        f"// Scopes: {scopes}\n"
        "\n"
        f"export const HAILER_KNOWLEDGE_CORPUS = `{escaped}`;\n"
        "\n"
        "export const HAILER_KNOWLEDGE_BYTES = HAILER_KNOWLEDGE_CORPUS.length;\n"
    )

    os.makedirs(os.path.dirname(OUTPUT_TS), exist_ok=True)
    with open(OUTPUT_TS, "w") as f:
        f.write(ts)

    print(f"Wrote {OUTPUT_TS}")
    print(f"Corpus size: {len(corpus):,} chars (~{len(corpus) // 4:,} tokens)")
    print(f"Total chunks: {total_chunks}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
