#!/usr/bin/env python3
"""
File verification tool for PHP migration tracking system.
Checks which files exist on filesystem and generates missing file reports.
"""

import os
import sys
from typing import List, Dict
from db_utils import MigrationDB

def verify_all_files(base_path: str = '../vmserver10/intranet') -> Dict[str, any]:
    """Verify all files in database exist on filesystem."""
    db = MigrationDB()
    
    print("🔍 Verifying file existence...")
    print(f"Base path: {os.path.abspath(base_path)}")
    
    stats = db.verify_all_files_exist(base_path)
    
    print(f"\n📊 Verification Results:")
    print(f"   Total files: {stats['total']}")
    print(f"   Files found: {stats['exists']}")
    print(f"   Missing files: {stats['missing']}")
    
    if stats['missing'] > 0:
        print(f"\n⚠️  {stats['missing']} files are missing from filesystem")
    else:
        print(f"\n✅ All files found on filesystem!")
    
    return stats

def list_missing_files(show_paths: bool = True) -> List[Dict]:
    """List all missing files."""
    db = MigrationDB()
    missing_files = db.get_missing_files()
    
    if not missing_files:
        print("✅ No missing files found!")
        return missing_files
    
    print(f"❌ Missing Files ({len(missing_files)}):")
    print("=" * 50)
    
    for i, file_record in enumerate(missing_files, 1):
        path = db.get_file_path(file_record)
        status = file_record['status']
        notes = file_record.get('notes', '')
        
        print(f"{i:3d}. {path} ({status})")
        
        if show_paths:
            full_path = db.get_full_filesystem_path(file_record)
            print(f"     Expected at: {full_path}")
        
        if notes and 'Auto-discovered' in notes:
            print(f"     Note: {notes}")
        
        print()
    
    return missing_files

def generate_missing_files_list(output_file: str = None) -> str:
    """Generate a list of missing files for collection from server."""
    db = MigrationDB()
    missing_files = db.get_missing_files()
    
    if output_file is None:
        from datetime import datetime
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        output_file = f'../Progress/missing_files_{timestamp}.txt'
    
    with open(output_file, 'w') as f:
        f.write("# Missing PHP Files - Need to Collect from Server\n")
        f.write(f"# Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write(f"# Total missing files: {len(missing_files)}\n\n")
        
        # Group by primary folder
        by_folder = {}
        for file_record in missing_files:
            folder = file_record['primary_folder'] or '(root)'
            if folder not in by_folder:
                by_folder[folder] = []
            by_folder[folder].append(file_record)
        
        for folder, files in sorted(by_folder.items()):
            f.write(f"## {folder} ({len(files)} files)\n")
            for file_record in files:
                path = db.get_file_path(file_record)
                full_path = db.get_full_filesystem_path(file_record)
                f.write(f"{path}\n")
                f.write(f"  -> {full_path}\n")
            f.write("\n")
    
    print(f"📝 Missing files list saved to: {output_file}")
    return output_file

def check_specific_files(file_paths: List[str], base_path: str = '../vmserver10/intranet') -> Dict[str, bool]:
    """Check if specific files exist."""
    results = {}
    
    print(f"🔍 Checking {len(file_paths)} specific files...")
    
    for file_path in file_paths:
        full_path = os.path.join(base_path, file_path.lstrip('/'))
        exists = os.path.exists(full_path)
        results[file_path] = exists
        
        status_icon = "✅" if exists else "❌"
        print(f"   {status_icon} {file_path}")
    
    found = sum(results.values())
    missing = len(file_paths) - found
    
    print(f"\n📊 Results: {found} found, {missing} missing")
    return results

def update_file_existence_from_filesystem(base_path: str = '../vmserver10/intranet'):
    """Update database file_exists flags based on current filesystem state."""
    db = MigrationDB()
    
    print("🔄 Updating file existence flags from filesystem...")
    
    all_files = db.get_all_files()
    updated = 0
    
    for file_record in all_files:
        file_path = db.get_full_filesystem_path(file_record, base_path)
        exists = os.path.exists(file_path)
        current_exists = bool(file_record.get('file_exists', 1))
        
        if exists != current_exists:
            db.update_file_flags(file_record['id'], file_exists=int(exists))
            updated += 1
            
            status = "found" if exists else "missing"
            print(f"   Updated: {db.get_file_path(file_record)} -> {status}")
    
    print(f"✅ Updated {updated} file existence flags")

def main():
    """Main verification function."""
    import argparse
    
    parser = argparse.ArgumentParser(description='Verify PHP file existence')
    parser.add_argument('--base-path', default='../vmserver10/intranet',
                       help='Base directory for PHP files')
    parser.add_argument('--list-missing', action='store_true',
                       help='List all missing files')
    parser.add_argument('--generate-list', action='store_true',
                       help='Generate missing files list for server collection')
    parser.add_argument('--output-file', 
                       help='Output file for missing files list')
    parser.add_argument('--check-files', nargs='+',
                       help='Check specific files (space-separated paths)')
    parser.add_argument('--update-flags', action='store_true',
                       help='Update database flags from filesystem')
    parser.add_argument('--no-paths', action='store_true',
                       help='Don\'t show full paths in missing files list')
    
    args = parser.parse_args()
    
    print("🔍 PHP File Verification Tool")
    print("=" * 40)
    
    if args.check_files:
        check_specific_files(args.check_files, args.base_path)
    elif args.list_missing:
        list_missing_files(not args.no_paths)
    elif args.generate_list:
        generate_missing_files_list(args.output_file)
    elif args.update_flags:
        update_file_existence_from_filesystem(args.base_path)
    else:
        # Default: verify all files
        stats = verify_all_files(args.base_path)
        
        if stats['missing'] > 0:
            print(f"\nTo see missing files: python3 verify_files.py --list-missing")
            print(f"To generate collection list: python3 verify_files.py --generate-list")

if __name__ == '__main__':
    main()