"""
Fix Morizon cookie handling timeout issue.

This script updates NetworkMonitoredPage records to include proper cookie selectors
so that the handle_cookies() function can quickly accept cookies instead of trying
dynamic detection which takes 4+ minutes per page.
"""

import os
import sys
import django

# Setup Django
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NetworkMonitoring.settings')
django.setup()

from extractly.models import NetworkMonitoredPage, SourceNetwork

def fix_morizon_cookies():
    """Add cookie configuration to Morizon pages to speed up cookie handling."""
    
    print("="*60)
    print("Fixing Morizon Cookie Timeout Issue")
    print("="*60)
    print()
    
    # Get Morizon source
    morizon_source = SourceNetwork.objects.filter(name='Morizon').first()
    if not morizon_source:
        print("ERROR: Morizon source not found!")
        return 0
    
    print(f"✓ Found Morizon source: {morizon_source.id}")
    print(f"  Base URL: {morizon_source.base_url}")
    
    # Cookie configuration - fast selectors for Morizon
    cookie_selectors = {
        "cookie_selector": "button.cmp-intro_acceptAll, button[aria-label*='Przejdź'], button.sv__btn-close, button[aria-label*='Close']",
        "cookie_text": "Przejdź do serwisu",
        "cookie_timeout": 10000  # 10 seconds
    }
    
    # Update all Morizon pages
    pages = NetworkMonitoredPage.objects.filter(source_id=morizon_source.id)
    total = pages.count()
    
    print(f"\n✓ Found {total} Morizon pages")
    print(f"\nUpdating pages with cookie configuration...")
    
    # Update in batches
    updated = 0
    batch_size = 100
    
    for i in range(0, total, batch_size):
        batch = pages[i:i+batch_size]
        
        for page in batch:
            if not page.meta:
                page.meta = {}
            
            # Add/update cookie selectors
            page.meta.update(cookie_selectors)
            page.save(update_fields=['meta'])
            updated += 1
        
        print(f"  Progress: {updated}/{total} pages...", end='\r')
    
    print(f"\n\n{'='*60}")
    print(f"✅ SUCCESS! Updated {updated} Morizon pages")
    print("="*60)
    print("\nCookie settings added:")
    print("  - Selector: button.cmp-intro_acceptAll")
    print("  - Timeout: 10 seconds (reduced from 45s)")
    print("  - Will skip slow dynamic detection")
    print("\n" + "="*60)
    print("Next steps:")
    print("1. Stop any running parallel_run_html.py (Ctrl+C)")
    print("2. Restart with:")
    print("   python scripts/parallel_run_html.py --name morizon --workers 4 --headless")
    print("3. Pages should now process in ~20-30s instead of 10+ minutes!")
    print("="*60)
    
    return updated

if __name__ == '__main__':
    try:
        updated = fix_morizon_cookies()
        sys.exit(0 if updated > 0 else 1)
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
