#!/usr/bin/env python3
"""Structural checks for the Dorota quark. Run before tagging a release.

    python3 tools/check_quark.py

Exits non-zero on any FAIL. Checks only what can be checked without sclang;
a green run here does not replace a compile test in a clean SuperCollider
support directory.
"""

import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
FAILS: list[str] = []
WARNS: list[str] = []


def fail(msg: str) -> None:
    FAILS.append(msg)


def warn(msg: str) -> None:
    WARNS.append(msg)


def check_layout() -> None:
    for rel in ("Dorota.quark", "Classes", "Core", "HelpSource", "README.md", "LICENSE"):
        if not (ROOT / rel).exists():
            fail(f"missing {rel}")


def check_quark_file() -> None:
    path = ROOT / "Dorota.quark"
    if not path.exists():
        return
    text = path.read_text(encoding="utf-8")
    if not text.lstrip().startswith("("):
        fail("Dorota.quark must be a parenthesised dictionary literal")
    for key in ("name:", "version:", "url:", "license:", "schelp:"):
        if key not in text:
            fail(f"Dorota.quark lacks {key}")
    m = re.search(r'version:\s*"([^"]+)"', text)
    if m:
        if not re.fullmatch(r"\d+\.\d+\.\d+", m.group(1)):
            fail(f"version {m.group(1)!r} is not semantic (x.y.z)")
        return m.group(1)
    fail("no version string in Dorota.quark")
    return None


def check_version_agreement(quark_version) -> None:
    src = (ROOT / "Classes" / "Dorota.sc").read_text(encoding="utf-8")
    m = re.search(r'classvar\s+<version\s*=\s*"([^"]+)"', src)
    if not m:
        fail("Dorota.sc declares no version classvar")
    elif quark_version and m.group(1) != quark_version:
        fail(f"version mismatch: Dorota.quark {quark_version} vs Dorota.sc {m.group(1)}")


def check_class_names() -> None:
    """Every .sc file should define a class matching its filename, and class
    names live in one global namespace — flag anything unprefixed."""
    declared = {}
    for path in sorted((ROOT / "Classes").glob("*.sc")):
        text = path.read_text(encoding="utf-8")
        names = re.findall(r"^([A-Z]\w*)\s*(?::\s*\w+\s*)?\{", text, re.M)
        if not names:
            fail(f"{path.name}: no class declaration found")
            continue
        if path.stem not in names:
            fail(f"{path.name}: defines {names}, expected a class named {path.stem}")
        for n in names:
            if n in declared:
                fail(f"class {n} declared in both {declared[n]} and {path.name}")
            declared[n] = path.name
        for n in names:
            if not n.startswith(("Dorota", "ATS", "Z354")):
                warn(f"{path.name}: class {n} has no project prefix — collision risk")
    return declared


def check_compile_time_side_effects() -> None:
    """*initClass runs while the class library compiles, before any server
    exists. SynthDef.add or Server access there breaks sclang startup."""
    for path in sorted((ROOT / "Classes").glob("*.sc")):
        text = path.read_text(encoding="utf-8")
        m = re.search(r"\*initClass\s*\{", text)
        if not m:
            continue
        depth, i = 0, m.end() - 1
        while i < len(text):
            if text[i] == "{":
                depth += 1
            elif text[i] == "}":
                depth -= 1
                if depth == 0:
                    break
            i += 1
        body = text[m.end():i]
        for pattern, what in (
            (r"SynthDef\s*\(", "SynthDef"),
            (r"Server\.", "Server access"),
            (r"\.boot\b", "server boot"),
            (r"Window\s*\(", "GUI construction"),
        ):
            if re.search(pattern, body):
                fail(f"{path.name}: *initClass contains {what} — runs at compile time")


def check_core_files() -> None:
    src = (ROOT / "Classes" / "Dorota.sc").read_text(encoding="utf-8")
    listed = re.findall(r'"(Core_[\w]+\.scd)"', src)
    if not listed:
        fail("Dorota.sc lists no core files")
        return
    on_disk = {p.name for p in (ROOT / "Core").glob("Core_*.scd")}
    for name in listed:
        if name not in on_disk:
            fail(f"Dorota.sc loads {name}, which is not in Core/")
    for name in sorted(on_disk - set(listed)):
        warn(f"Core/{name} is never loaded by Dorota.sc")
    if listed.index("Core_05.scd") < max(
        listed.index(n) for n in ("Core_01.scd", "Core_02.scd", "Core_04.scd") if n in listed
    ):
        fail("Core_05 (GUI) must load after its helper cores")


def check_help() -> None:
    for path in sorted((ROOT / "Classes").glob("*.sc")):
        help_path = ROOT / "HelpSource" / "Classes" / f"{path.stem}.schelp"
        if not help_path.exists():
            warn(f"no help file for {path.stem}")


def check_balanced() -> None:
    """Cheap syntax smoke test: unbalanced braces mean the class library will
    not compile, and an uncompilable quark leaves users with a dead sclang."""
    for path in sorted(list((ROOT / "Classes").glob("*.sc")) + list((ROOT / "Core").glob("*.scd"))):
        text = path.read_text(encoding="utf-8")
        text = re.sub(r"//[^\n]*", "", text)
        text = re.sub(r'"(?:[^"\\]|\\.)*"', '""', text)
        text = re.sub(r"\$.", "", text)
        for open_ch, close_ch in (("{", "}"), ("(", ")"), ("[", "]")):
            delta = text.count(open_ch) - text.count(close_ch)
            if delta:
                fail(f"{path.name}: {abs(delta)} unmatched {open_ch if delta > 0 else close_ch}")


def main() -> int:
    check_layout()
    version = check_quark_file()
    check_version_agreement(version)
    check_class_names()
    check_compile_time_side_effects()
    check_core_files()
    check_help()
    check_balanced()

    for w in WARNS:
        print(f"WARN  {w}")
    for f in FAILS:
        print(f"FAIL  {f}")
    if FAILS:
        print(f"\n{len(FAILS)} failure(s), {len(WARNS)} warning(s)")
        return 1
    print(f"\nOK — {len(WARNS)} warning(s)")
    return 0


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