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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
ROOT="${AGENTTEAM_MESHX_RUNTIME_TOPOLOGY_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
cd "$ROOT"

go run "$SCRIPT_DIR/check-meshx-runtime-topology.go" "$ROOT"

python3 - <<'PY'
import sys
import re
from pathlib import Path

root = Path.cwd()
failures = []

if (root / "cmd/meshx-server").exists():
    failures.append("cmd/meshx-server: standalone MeshX command must not exist")
if (root / "meshx").exists():
    failures.append("meshx: retired MeshX physical source root must not exist")
if (root / "internal/meshx").exists():
    failures.append("internal/meshx: retired transitional source namespace must not be recreated")
resource_server = root / "internal/resource/server"
if not resource_server.is_dir():
    failures.append("internal/resource/server: resource runtime composition owner is missing")
else:
    for module_file in sorted(
        path for name in ("go.mod", "go.sum") for path in resource_server.rglob(name)
    ):
        failures.append(
            f"{module_file.relative_to(root).as_posix()}: resource server must not be a nested Go module"
        )
if (root / "internal/embeddedmeshx").exists():
    failures.append("internal/embeddedmeshx: retired handler transport facade must not exist")

active_roots = [
    root / "cmd",
    root / "dev",
    root / "internal",
    root / "x/proc",
    root / "scripts",
    root / "guardrails",
    root / "specs",
    root / "e2e",
    root / "docs/operations",
    root / "docs/development.md",
    root / "docs/tech_design.md",
    root / "SKILL_MEMORY_AGS_PERMISSION_MATRIX.md",
    root / "web/src",
    root / "docker",
]
active_files = set()
for active_root in active_roots:
    if active_root.is_file():
        active_files.add(active_root)
    elif active_root.exists():
        active_files.update(path for path in active_root.rglob("*") if path.is_file())
for pattern in ("Dockerfile*", "Makefile", "docker-compose*.yml", "docker-compose*.yaml"):
    active_files.update(path for path in root.glob(pattern) if path.is_file())

fixture_sources = {
    root / "guardrails/architecture/check-meshx-service-boundaries.sh",
    root / "guardrails/architecture/check-meshx-runtime-topology.sh",
    root / "guardrails/architecture/check-meshx-runtime-topology-test.sh",
}
retired_server_fixture_lines = {
    (
        "scripts/agentteam-prod-activate-release.test.mjs",
        'assert.ok(!existsSync(join(target, "bin", "meshx-server")))',
    ),
    (
        "x/proc/tree_test.go",
        '{PID: 20, Command: filepath.Join(binDir, "meshx-server")},',
    ),
}
old_physical_path = re.compile(r"(?<!internal/)meshx/(?:runtime|handlertransport|schema|internal)(?:/|\b)")
retired_internal_path = re.compile(r"(?:^|[^A-Za-z0-9_])internal/meshx(?:/|\b)")
retired_module_path = re.compile(r"go\.pingcap\.cn/meshx(?:/|\b)")

root_go_mod = root / "go.mod"
if root_go_mod.exists():
    for line_no, line in enumerate(root_go_mod.read_text(errors="ignore").splitlines(), start=1):
        if "go.pingcap.cn/meshx" in line.split():
            failures.append(
                f"go.mod:{line_no}: root module must not require or replace go.pingcap.cn/meshx"
            )

for path in sorted(active_files):
    if path in fixture_sources or "testdata" in path.parts:
        continue
    text = path.read_text(errors="ignore")
    rel = path.relative_to(root).as_posix()
    canonical_text = rel.startswith("specs/") or rel.startswith("docs/") or rel == "SKILL_MEMORY_AGS_PERMISSION_MATRIX.md"
    for line_no, line in enumerate(text.splitlines(), start=1):
        retired_server_fixture = (rel, line.strip()) in retired_server_fixture_lines
        if not canonical_text and "meshx-server" in line and not retired_server_fixture:
            failures.append(
                f"{rel}:{line_no}: standalone meshx-server production residue is forbidden"
            )
        if not canonical_text and "MESHX_HTTP_ADDRESS" in line:
            failures.append(
                f"{rel}:{line_no}: retired standalone listener environment is forbidden"
            )
        if "github.com/tidbcloud/AgentTeam/meshx" in line:
            failures.append(f"{rel}:{line_no}: retired MeshX import root is forbidden")
        if retired_module_path.search(line):
            failures.append(f"{rel}:{line_no}: retired MeshX module import is forbidden")
        if old_physical_path.search(line):
            failures.append(f"{rel}:{line_no}: retired MeshX physical path is forbidden")
        if retired_internal_path.search(line):
            failures.append(f"{rel}:{line_no}: retired internal/meshx namespace is forbidden")

proc_tree = root / "x/proc/tree.go"
if proc_tree.exists() and 'filepath.Join(repoRoot, "meshx")' in proc_tree.read_text(errors="ignore"):
    failures.append(
        "x/proc/tree.go: the retired MeshX source root must not be treated as a runnable dev-process cwd"
    )

if failures:
    print("MeshX unified-runtime topology guardrail failed:", file=sys.stderr)
    for failure in failures:
        print(f"- {failure}", file=sys.stderr)
    sys.exit(1)

print("MeshX unified-runtime topology guardrail passed")
PY
