"""Prepare separate Doxygen layouts and CMake metadata from the language manifest.

Called at CMake configure time by portals_docs. Required inputs are the language
manifest and layout XML with one navindex language="CODE" per configured language.
Writes languages.cmake and layout-CODE.xml into --output; existing generated files
are overwritten. Source files are read only. No network or Doxygen invocation.
Prints generated language codes; exits 0 on success, 1 for invalid data or I/O,
and 2 for invalid command syntax. --help requires no inputs and creates no files.
"""

import argparse
import copy
import html
import json
from pathlib import Path, PurePosixPath
import re
import sys
import xml.etree.ElementTree as ET
from urllib.parse import unquote, urlsplit


def relative_path(value, field, allow_empty=False):
    """Validate repository/output paths before embedding them in CMake code."""
    if not isinstance(value, str) or (not value and not allow_empty):
        raise ValueError(f"{field} must be a relative path")
    path = PurePosixPath(value)
    if (path.is_absolute() or ".." in path.parts or re.search(r'[\\:;"$\r\n]', value)
            or (value and value != path.as_posix()) or value == "."):
        raise ValueError(f"{field} must be a portable relative path: {value!r}")
    return value


def load_languages(manifest):
    """Return validated locale metadata with the default locale first."""
    config = json.loads(manifest.read_text(encoding="utf-8"))
    languages = config.get("languages")
    if not isinstance(languages, list) or not languages:
        raise ValueError("languages must be a nonempty list")
    codes, directories = set(), set()
    for language in languages:
        code = language.get("code", "")
        if not re.fullmatch(r"[a-z]{2,3}(?:-[A-Z]{2})?", code) or code in codes:
            raise ValueError(f"Invalid or duplicate language code: {code!r}")
        codes.add(code)
        directory = relative_path(language.get("directory"), "directory", allow_empty=True)
        if directory in directories:
            raise ValueError(f"Duplicate output directory: {directory!r}")
        directories.add(directory)
        relative_path(language.get("source"), "source")
        relative_path(language.get("main"), "main")
        if not language["main"].startswith(language["source"] + "/"):
            raise ValueError(f"Main page must be inside source: {code}")
        if not re.fullmatch(r"[A-Za-z_-]+", language.get("output_language", "")):
            raise ValueError(f"Invalid Doxygen output language: {code}")
        if not isinstance(language.get("name"), str) or not language["name"]:
            raise ValueError(f"Missing language name: {code}")
    default = config.get("default")
    if default not in codes:
        raise ValueError("default must name a configured language")
    languages.sort(key=lambda item: item["code"] != default)
    if languages[0]["directory"]:
        raise ValueError("The default language must use the root output directory")
    for language in languages[1:]:
        if not language["directory"]:
            raise ValueError("Only the default language can use the root output directory")
    return languages


def prepare(manifest, layout, output):
    """Validate all inputs, then generate language-specific build metadata/layouts."""
    languages = load_languages(manifest)
    root = ET.parse(layout).getroot()
    layouts = {}
    for language in languages:
        code = language["code"]
        candidates = root.findall(f"navindex[@language='{code}']")
        if len(candidates) != 1:
            raise ValueError(f"Expected exactly one navindex language={code!r}")
        localized = ET.Element(root.tag, root.attrib)
        navigation = copy.deepcopy(candidates[0])
        del navigation.attrib["language"]
        for tab in navigation.iter("tab"):
            if tab.get("url") == "@ref " + language["main"]:
                tab.set("url", "index.html")
        localized.append(navigation)
        for element in root:
            if element.tag != "navindex":
                localized.append(copy.deepcopy(element))
        ET.indent(localized)
        layouts[code] = ET.tostring(localized, encoding="unicode", xml_declaration=True) + "\n"
    metadata = ["# Generated by tools/docs/prepare_languages.py; do not edit.",
                'set(portals_doc_languages "' + ";".join(item["code"] for item in languages) + '")']
    for language in languages:
        for field in ("directory", "source", "main", "output_language"):
            metadata.append(f'set(portals_doc_{language["code"]}_{field} "{language[field]}")')
    output.mkdir(parents=True, exist_ok=True)
    for code, content in layouts.items():
        (output / f"layout-{code}.xml").write_text(content, encoding="utf-8")
    (output / "languages.cmake").write_text("\n".join(metadata) + "\n", encoding="utf-8")
    return [language["code"] for language in languages]


def filter_document(manifest, source_root, language, path):
    """Leave foreign Markdown links as HTML for post-build language resolution.

    Doxygen calls this input filter with an original filename. It must preserve
    source line numbers and code fences, write only filtered text to stdout, and
    never rewrite the original file. Other input formats pass through unchanged.
    """
    content = path.read_text(encoding="utf-8")
    if path.suffix.lower() != ".md":
        return content
    languages = load_languages(manifest)
    if language not in {item["code"] for item in languages}:
        raise ValueError(f"Unknown input-filter language: {language}")
    default = languages[0]["code"]
    ordered = sorted(languages, key=lambda item: len(item["source"]), reverse=True)

    def link(match):
        target = match[2]
        url = urlsplit(target)
        if url.scheme or url.netloc or not url.path.endswith(".md"):
            return match[0]
        resolved = (path.parent / unquote(url.path)).resolve()
        try:
            relative = resolved.relative_to(source_root.resolve()).as_posix()
        except ValueError:
            return match[0]
        owner = next((item["code"] for item in ordered
                      if relative.startswith(item["source"] + "/")), default)
        main_page = next(item["main"] for item in languages if item["code"] == language)
        if owner == language and relative != main_page:
            return match[0]
        return f'<a href="{html.escape(target, quote=True)}">{match[1]}</a>'

    lines = []
    fence = None
    for line in content.splitlines(keepends=True):
        boundary = re.match(r"^\s{0,3}(`{3,}|~{3,})", line)
        if boundary:
            marker = boundary[1]
            if fence is None:
                fence = marker
            elif marker[0] == fence[0] and len(marker) >= len(fence):
                fence = None
            lines.append(line)
        elif fence is not None:
            lines.append(line)
        else:
            # Inline code is also literal source, even if it looks like a link.
            parts = re.split(r"(`+[^`]*`+)", line)
            for index in range(0, len(parts), 2):
                parts[index] = re.sub(r"\[([^\]\n]+)\]\(([^\s)]+)\)", link, parts[index])
            lines.append("".join(parts))
    return "".join(lines)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("manifest", type=Path, help="Language JSON manifest")
    parser.add_argument("layout", type=Path, nargs="?", help="Layout XML with localized navindex elements")
    parser.add_argument("--output", type=Path, help="Generated files directory (overwritten)")
    parser.add_argument("--filter-language", help="Internal Doxygen input-filter language code")
    parser.add_argument("--source-root", type=Path, help="Repository root for the input filter")
    parser.add_argument("--filter-input", type=Path, help="Input filename appended by Doxygen; read only")
    args = parser.parse_args()
    if args.filter_language:
        if not args.source_root or not args.filter_input:
            parser.error("--filter-language requires --source-root and --filter-input")
    elif not args.layout or not args.output:
        parser.error("layout and --output are required when preparing languages")
    try:
        if args.filter_language:
            sys.stdout.reconfigure(encoding="utf-8")
            sys.stdout.write(filter_document(args.manifest, args.source_root,
                                            args.filter_language, args.filter_input))
        else:
            print(json.dumps({"languages": prepare(args.manifest, args.layout, args.output)}))
    except (OSError, ValueError, TypeError, AttributeError, ET.ParseError) as error:
        print(f"prepare_languages: {error}", file=sys.stderr)
        return 1
    return 0


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