#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Emit normalized test inventory records for lairu.org status generation."""

from __future__ import annotations

import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
REFERENCE_PROBE_FILES = {"knop9_probe.rs", "rope_probe.rs"}


def normalize(value: str) -> str:
    value = value.lower()
    value = re.sub(r"\s+", "_", value)
    for old, new in [
        ("->", "_"),
        ("::", "_"),
        ("/", "_"),
        ("\\", "_"),
        ("-", "_"),
        (".", "_"),
        ("(", "_"),
        (")", "_"),
        (",", "_"),
        ("'", "_"),
        ('"', "_"),
        (":", "_"),
        ("=", "_"),
        ("|", "_"),
    ]:
        value = value.replace(old, new)
    while "__" in value:
        value = value.replace("__", "_")
    return value.strip("_")


def rust_test_records() -> list[tuple[str, str]]:
    records: list[tuple[str, str]] = []
    test_re = re.compile(r"#\[test\]\s*(?:\n\s*#\[[^\n]+\]\s*)*\n\s*fn\s+([A-Za-z0-9_]+)\s*\(")
    for path in sorted((ROOT / "src").rglob("*.rs")) + sorted((ROOT / "tests").glob("*.rs")):
        if path.name in REFERENCE_PROBE_FILES:
            continue
        source = path.read_text(errors="ignore")
        matches = list(test_re.finditer(source))
        for index, match in enumerate(matches):
            name = match.group(1)
            start = match.start()
            end = matches[index + 1].start() if index + 1 < len(matches) else len(source)
            body = source[start:end]
            rel = path.relative_to(ROOT)
            records.append((normalize(name + "\n" + body), f"{rel}::{name}"))
    return records


def fixture_records() -> list[tuple[str, str]]:
    records: list[tuple[str, str]] = []
    fixtures = ROOT / "tests" / "fixtures"
    for path in sorted(fixtures.rglob("*.lasso")):
        rel = path.relative_to(ROOT)
        stem = path.stem
        body = path.read_text(errors="ignore")
        records.append((normalize(stem + "\n" + body), str(rel)))
    return records


def main() -> None:
    seen: set[str] = set()
    for key, label in fixture_records() + rust_test_records():
        if not key or label in seen:
            continue
        seen.add(label)
        print(f"{key}|{label}")


if __name__ == "__main__":
    main()
