#!/usr/bin/env python3
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from harness import LintWarning, repo_check
from shared.paths import SRC_DIR

# ---@trx.module N above `local M = h.module("name")` - the order the module
# takes in the generated reference. Two modules sharing one leave their pages
# in the order the sort happens to settle on.
MODULE_RE = re.compile(
    r"""---@trx\.module\s+(\d+)[^\n]*\n(?:---[^\n]*\n)*"""
    r"""local\s+\w+\s*=\s*h\.module\("([^"]+)"\)"""
)


def modules_of(text):
    for match in MODULE_RE.finditer(text):
        yield match.group(2), int(match.group(1)), match.start()


def check():
    api_dir = SRC_DIR / "lua/trx"
    seen: dict[int, tuple[Path, str]] = {}
    for path in sorted(api_dir.glob("*.lua")):
        text = path.read_text(encoding="utf-8")
        for name, order, start in modules_of(text):
            line = text.count("\n", 0, start) + 1
            if order in seen:
                other_path, other_name = seen[order]
                yield LintWarning(
                    path,
                    f"module '{name}' takes order {order}, "
                    f"which '{other_name}' already has "
                    f"({other_path.relative_to(SRC_DIR.parent)})",
                    line=line,
                )
                continue
            seen[order] = (path, name)


repo_check(check)
