#!/usr/bin/env bash
set -euo pipefail

ROOT="${AGENTTEAM_REPO_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)}"

python3 - "$ROOT" <<'PY'
from pathlib import Path
import re
import sys

root = Path(sys.argv[1])
web_src = root / "web" / "src"
reload_helper = "web/src/agentteam/reloadReasonTelemetry.ts"
source_file = re.compile(r"\.(ts|tsx)$")
failures: list[str] = []


def rel(path: Path) -> str:
    return path.relative_to(root).as_posix()


def source_files(*roots: Path):
    for source_root in roots:
        if not source_root.exists():
            continue
        for path in source_root.rglob("*"):
            if not path.is_file() or not source_file.search(path.name):
                continue
            if ".test." in path.name or path.name.endswith(".d.ts"):
                continue
            yield path


# All document reloads must go through reloadWithReason(), so the automatic
# reload paths leave a pending reload_reason marker before the page unloads.
for path in source_files(web_src):
    text = path.read_text()
    if "window.location.reload(" not in text and "location.reload(" not in text:
        continue
    relative = rel(path)
    if relative == reload_helper:
        continue
    for index, line in enumerate(text.splitlines(), 1):
        if "location.reload(" in line:
            failures.append(
                f"{relative}:{index}: call reloadWithReason(...) instead of direct location.reload()"
            )

anchor_pattern = re.compile(r"<a\b(?P<body>.*?)(?:</a>|/>)", re.S)
workspace_roots = (web_src / "agentteam", web_src / "shell")


def line_number(text: str, offset: int) -> int:
    return text.count("\n", 0, offset) + 1


def is_internal_anchor(block: str, file_text: str) -> bool:
    if 'href="/w' in block or "href={'/w" in block:
        return True
    if "buildWorkspacePath(" in block:
        return True
    if "href={taskHref}" in block:
        return True
    if "knowledgeTarget" in block or "internalTarget" in block:
        return True
    if "href={href}" in block and (
        "relatedTaskHref(" in file_text or "taskScopeHref(" in file_text
    ):
        return True
    return False


def uses_router_navigate(block: str) -> bool:
    return "preventDefault()" in block and re.search(r"\bnavigate\s*\(", block) is not None


for path in source_files(*workspace_roots):
    text = path.read_text()
    for match in anchor_pattern.finditer(text):
        block = match.group(0)
        if "href=" not in block or not is_internal_anchor(block, text):
            continue
        if uses_router_navigate(block):
            continue
        failures.append(
            f"{rel(path)}:{line_number(text, match.start())}: internal raw anchor must preventDefault() and use Router navigate()"
        )

if failures:
    print("Web reload/internal-navigation guardrail failed:", file=sys.stderr)
    for failure in failures:
        print(f"  - {failure}", file=sys.stderr)
    raise SystemExit(1)

print("Web reload/internal-navigation guardrail passed.")
PY
