#!/usr/bin/env python3
"""
WCP ID Migration: Strip .v1 suffix from all capability, worker, control, policy, profile, and event IDs.
Targets: pyhall/*.py, pyhall/tests/*.py, workforce-os JSON files.
"""

import re
import sys
from pathlib import Path

# Pattern matches quoted IDs like "cap.doc.summarize.v1" — any prefix type, any dot-path, any .vN suffix
ID_PATTERN = re.compile(r'("(?:cap|wrk|ctrl|pol|prof|evt)\.[a-z0-9._-]+)\.v\d+"')
ID_REPLACEMENT = r'\1"'

TARGET_DIRS_JSON = [
    Path("/mnt/fafolab/dev/workforce-os/registry/artifacts"),
    Path("/mnt/fafolab/dev/workforce-os/registry/enrolled"),
]

TARGET_WORKERS_PATTERNS = [
    "/mnt/fafolab/dev/workforce-os/workers/**/registry_record.json",
    "/mnt/fafolab/dev/workforce-os/workers/**/routing_rule_snippet.json",
]

TARGET_PY = [
    Path("/mnt/fafolab/dev/pyhall/pyhall"),
    Path("/mnt/fafolab/dev/pyhall/tests"),
]

# Also check WCP_SPEC.md
EXTRA_MD = [
    Path("/mnt/fafolab/dev/wcp/WCP_SPEC.md"),
    Path("/mnt/fafolab/dev/pyhall/WCP_SPEC.md"),
]

total_replacements = 0
files_changed = []


def migrate_content(content: str) -> tuple[str, int]:
    """Apply the regex replacement and return (new_content, count)."""
    new_content, n = ID_PATTERN.subn(ID_REPLACEMENT, content)
    return new_content, n


def process_file(path: Path) -> int:
    """Read, migrate, write if changed. Returns replacement count."""
    try:
        original = path.read_text(encoding="utf-8")
    except Exception as e:
        print(f"  ERROR reading {path}: {e}")
        return 0

    new_content, n = migrate_content(original)
    if n > 0:
        path.write_text(new_content, encoding="utf-8")
        print(f"  CHANGED ({n:3d} replacements): {path}")
        return n
    return 0


def collect_json_files() -> list[Path]:
    files = []
    for d in TARGET_DIRS_JSON:
        if d.exists():
            files.extend(d.glob("*.json"))
        else:
            print(f"  WARN: directory not found: {d}")

    for pattern in TARGET_WORKERS_PATTERNS:
        base = Path("/mnt/fafolab/dev/workforce-os/workers")
        for p in base.glob("**/registry_record.json"):
            files.append(p)
        for p in base.glob("**/routing_rule_snippet.json"):
            files.append(p)
    return list(set(files))


def collect_py_files() -> list[Path]:
    files = []
    for d in TARGET_PY:
        if d.exists():
            files.extend(d.glob("*.py"))
        else:
            print(f"  WARN: directory not found: {d}")
    return files


def collect_md_files() -> list[Path]:
    files = []
    for p in EXTRA_MD:
        if p.exists():
            files.append(p)
    return files


print("=" * 60)
print("WCP ID Migration: Strip .vN suffix from WCP IDs")
print("=" * 60)
print()

print("[1/3] Processing JSON files...")
json_files = collect_json_files()
json_count = 0
for f in sorted(set(json_files)):
    n = process_file(f)
    if n > 0:
        json_count += n
        files_changed.append(str(f))
print(f"  JSON total replacements: {json_count}")
print()

print("[2/3] Processing Python files...")
py_files = collect_py_files()
py_count = 0
for f in sorted(py_files):
    n = process_file(f)
    if n > 0:
        py_count += n
        files_changed.append(str(f))
print(f"  Python total replacements: {py_count}")
print()

print("[3/3] Checking Markdown spec files for stray .vN IDs...")
md_files = collect_md_files()
md_count = 0
for f in sorted(md_files):
    # For spec files: report but don't blindly rewrite (IDs in spec might be intentional examples)
    try:
        content = f.read_text(encoding="utf-8")
    except Exception as e:
        print(f"  ERROR reading {f}: {e}")
        continue
    _, n = migrate_content(content)
    if n > 0:
        print(f"  FOUND {n} stray IDs in spec (not auto-migrated): {f}")
        print("  Review manually if these should be stripped.")
    else:
        print(f"  CLEAN: {f}")
print()

total_replacements = json_count + py_count + md_count
print("=" * 60)
print(f"MIGRATION COMPLETE")
print(f"  Total replacements:  {total_replacements}")
print(f"  Files changed:       {len(files_changed)}")
print()
if files_changed:
    print("Changed files:")
    for f in sorted(files_changed):
        print(f"  {f}")
print("=" * 60)
