import os
import re

# CMassY2 uses 'D', others use 'Q'
directories = ["CMassM1", "CMassK1", "CMassP1", "CMassY2"]
base_path = "/Volumes/Scratch/Sites"

def fix_registry(dir_name):
    cmass_path = os.path.join(base_path, dir_name)
    registry_path = os.path.join(cmass_path, ".smbatcher", "REGISTRY.md")
    sites_dir = os.path.join(cmass_path, "sites")
    
    if not os.path.exists(registry_path) or not os.path.exists(sites_dir):
        print(f"Skipping {dir_name}: Missing registry or sites dir")
        return

    print(f"Processing {dir_name}...")
    
    with open(registry_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    new_lines = []
    changes = 0
    
    for line in lines:
        # Match table row: | domain | title | desc | status | batch | updated |
        match = re.match(r'^\| ([^|]+) \| ([^|]+) \| ([^|]+) \| ([^|]+) \| ([^|]+) \| ([^|]+) \|$', line.strip())
        if match:
            domain = match.group(1).strip()
            status = match.group(4).strip()
            
            # Check if index.html exists for this domain
            site_v1_dir = os.path.join(sites_dir, f"{domain}-v1")
            index_path = os.path.join(site_v1_dir, "index.html")
            
            # CMassY2 uses 'D' as the pending/design status. Others use 'Q'.
            # If implementation exists (index.html), mark as 'O'.
            pending_statuses = ["Q", "D"]
            
            if os.path.exists(index_path) and status in pending_statuses:
                new_status = "O"
                new_line = line.replace(f"| {status} |", f"| {new_status} |")
                new_lines.append(new_line)
                changes += 1
                continue
        
        new_lines.append(line)

    if changes > 0:
        with open(registry_path, 'w', encoding='utf-8') as f:
            f.writelines(new_lines)
        print(f"  Fixed {changes} entries in {dir_name}")
    else:
        print(f"  No changes needed in {dir_name}")

for d in directories:
    fix_registry(d)
