"""
CORRECT fix for Morizon cookie handling.

The handle_cookies() function expects:
  meta["cookies"]["accept_selector"]
  meta["cookies"]["timeout"]

NOT:
  meta["cookie_selector"]
  meta["cookie_timeout"]

This script applies the CORRECT structure.
"""

import os
import sys
import 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_cookie_structure():
    """Fix cookie configuration structure."""
    
    print("="*70)
    print("CORRECT COOKIE FIX - Proper Structure")
    print("="*70)
    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 source: {morizon_source.id}")
    
    # CORRECT cookie configuration structure
    correct_cookies_config = {
        "cookies": {
            "accept_selector": "button.cmp-intro_acceptAll, button[aria-label*='Przejdź'], button.sv__btn-close, button[aria-label*='Close']",
            "accept_text": "Przejdź do serwisu",
            "timeout": 10000  # 10 seconds
        }
    }
    
    # Update all Morizon pages
    pages = NetworkMonitoredPage.objects.filter(source_id=morizon_source.id)
    total = pages.count()
    
    print(f"✓ Found {total} pages")
    print(f"\nApplying CORRECT cookie structure...")
    print("  meta['cookies']['accept_selector'] = ...")
    print("  meta['cookies']['timeout'] = 10000")
    print()
    
    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 = {}
            
            # Remove old incorrect keys FIRST (important!)
            page.meta.pop('cookie_selector', None)
            page.meta.pop('cookie_timeout', None)
            page.meta.pop('cookie_text', None)
            
            # Apply CORRECT structure
            page.meta['cookies'] = correct_cookies_config['cookies']
            
            page.save(update_fields=['meta'])
            updated += 1
        
        print(f"  Progress: {updated}/{total} pages...", end='\r')
    
    print(f"\n\n{'='*70}")
    print(f"✅ SUCCESS! Fixed {updated} pages with CORRECT structure")
    print("="*70)
    print("\nCookie config applied:")
    print("  meta = {")
    print("    'cookies': {")
    print("      'accept_selector': 'button.cmp-intro_acceptAll, ...',")
    print("      'accept_text': 'Przejdź do serwisu',")
    print("      'timeout': 10000")
    print("    }")
    print("  }")
    print("\n" + "="*70)
    print("NOW cookies will be accepted in 1-2 seconds!")
    print("="*70)
    print("\nRestart HTML collection:")
    print("  python scripts/parallel_run_html.py --name morizon --workers 4 --headless")
    print("="*70)
    
    return updated

if __name__ == '__main__':
    try:
        updated = fix_cookie_structure()
        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)
