#!/usr/bin/env python3
"""
Link fixer for PHP migration tracking system.
Fixes malformed links in PHP files by removing extra /intranet/ path components.
"""

import os
import sys
from pathlib import Path

class LinkFixer:
    """Fixer for malformed links in PHP files."""

    def __init__(self, base_path: str = '../vmserver10/intranet'):
        self.base_path = Path(base_path).resolve()

        # Malformed links and their corrections
        self.link_fixes = {
            '/$baseurl/intranet/databases/crm/HiddenRemovedContacts.php': '/$baseurl/databases/crm/HiddenRemovedContacts.php',
            '/<?php print "$baseurl";?>/intranet/databases/crm/crmlinkeddocuments.php': '/<?php print "$baseurl";?>/databases/crm/crmlinkeddocuments.php'
        }

    def fix_file(self, file_path: str) -> bool:
        """
        Fix malformed links in a single file.

        Args:
            file_path: Path to the file to fix

        Returns:
            True if file was modified, False otherwise
        """
        if not os.path.exists(file_path):
            return False

        try:
            with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
            return False

        original_content = content
        modified = False

        # Apply all link fixes
        for malformed, correct in self.link_fixes.items():
            if malformed in content:
                content = content.replace(malformed, correct)
                modified = True
                print(f"  Fixed: {malformed} -> {correct}")

        if modified:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                print(f"✅ Fixed links in {file_path}")
                return True
            except Exception as e:
                print(f"Error writing {file_path}: {e}")
                return False

        return False

    def fix_all_files(self) -> dict:
        """
        Fix malformed links in all PHP files in the base directory.

        Returns:
            Dictionary with fix statistics
        """
        stats = {
            'files_checked': 0,
            'files_fixed': 0,
            'errors': 0
        }

        if not self.base_path.exists():
            print(f"Base path does not exist: {self.base_path}")
            return stats

        print(f"🔧 Fixing malformed links in {self.base_path}...")

        # Walk through all PHP files
        for root, dirs, files in os.walk(self.base_path):
            for file in files:
                if file.endswith('.php'):
                    file_path = os.path.join(root, file)
                    stats['files_checked'] += 1

                    try:
                        if self.fix_file(file_path):
                            stats['files_fixed'] += 1
                    except Exception as e:
                        print(f"Error fixing {file_path}: {e}")
                        stats['errors'] += 1

                    # Progress update every 50 files
                    if stats['files_checked'] % 50 == 0:
                        print(f"   Processed {stats['files_checked']} files...")

        return stats

def main():
    """Main fixing function."""
    import argparse

    parser = argparse.ArgumentParser(description='Fix malformed links in PHP files')
    parser.add_argument('--base-path', default='../vmserver10/intranet', help='Base path for PHP files')
    parser.add_argument('--dry-run', action='store_true', help='Show what would be fixed without making changes')

    args = parser.parse_args()

    print("🔧 PHP Link Fixer")
    print("=" * 40)

    fixer = LinkFixer(args.base_path)

    if args.dry_run:
        print("DRY RUN - No files will be modified")
        # For dry run, we could implement a check mode, but for now just show the fixes
        print("Configured fixes:")
        for malformed, correct in fixer.link_fixes.items():
            print(f"  {malformed}")
            print(f"    -> {correct}")
        return

    stats = fixer.fix_all_files()

    print("\n✅ Fix complete:")
    print(f"   Files checked: {stats['files_checked']}")
    print(f"   Files fixed: {stats['files_fixed']}")
    print(f"   Errors: {stats['errors']}")

if __name__ == '__main__':
    main()