#!/usr/bin/env python3
"""
Script to replace old 'data.' schema references with new DDD schemas in SQL strings.
Only modifies SQL strings inside text() calls or raw strings.
"""

import os
import re
import sys
from pathlib import Path

# Mapping of old to new schemas
REPLACEMENTS = {
    "data.catalog_discovery": "vehicle.catalog_discovery",
    "data.vehicle_catalog": "vehicle.vehicle_catalog",
    "data.vehicle_model_definitions": "vehicle.vehicle_model_definitions",
    "data.service_staging": "marketplace.service_staging",
    "data.users": "identity.users",
    "data.organizations": "fleet.organizations",
    "data.system_parameters": "system.system_parameters",
    # Also handle potential variations with spaces or line breaks
}

# Compile regex patterns for each replacement
patterns = {old: re.compile(re.escape(old)) for old in REPLACEMENTS.keys()}

def process_file(filepath: Path):
    """Process a single Python file."""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
    except UnicodeDecodeError:
        print(f"  Skipping non-UTF-8 file: {filepath}")
        return False
    
    original = content
    modified = False
    
    # Apply each replacement
    for old, new in REPLACEMENTS.items():
        if old in content:
            # Use regex to replace only whole occurrences (avoid partial matches)
            new_content, count = patterns[old].subn(new, content)
            if count > 0:
                content = new_content
                modified = True
                print(f"    {old} -> {new} ({count} times)")
    
    if modified:
        # Backup original file
        backup = filepath.with_suffix(filepath.suffix + '.bak')
        if not backup.exists():
            with open(backup, 'w', encoding='utf-8') as f:
                f.write(original)
        
        # Write modified content
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
        return True
    return False

def main():
    base_dir = Path("/opt/docker/dev/service_finder/backend/app")
    if not base_dir.exists():
        print(f"Error: Directory not found: {base_dir}")
        sys.exit(1)
    
    print(f"Scanning Python files in {base_dir}...")
    modified_files = []
    
    for root, dirs, files in os.walk(base_dir):
        # Skip __pycache__ and .git directories
        dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']
        
        for file in files:
            if file.endswith('.py'):
                filepath = Path(root) / file
                print(f"Processing {filepath.relative_to(base_dir)}...")
                if process_file(filepath):
                    modified_files.append(str(filepath.relative_to(base_dir)))
    
    print("\n=== Summary ===")
    if modified_files:
        print(f"Modified {len(modified_files)} files:")
        for f in modified_files:
            print(f"  - {f}")
    else:
        print("No files needed modification.")
    
    # Also clean up old .veryold and .bak files (optional)
    print("\nCleaning up old backup files...")
    for root, dirs, files in os.walk(base_dir):
        for file in files:
            if file.endswith('.veryold') or file.endswith('.bak'):
                filepath = Path(root) / file
                try:
                    filepath.unlink()
                    print(f"  Deleted {filepath.relative_to(base_dir)}")
                except Exception as e:
                    print(f"  Failed to delete {filepath}: {e}")

if __name__ == "__main__":
    main()