#!/usr/bin/env python3
"""
Properstar Session Validator
Tests if auth.json session is still valid
"""
import asyncio
import os
import sys
from playwright.async_api import async_playwright

FAVORITES_URL = "https://www.properstar.nl/favorites"
AUTH_JSON = "auth.json"

async def validate_session():
    """
    Validate if the current auth.json session is still valid

    Returns:
        dict with status information
    """
    result = {
        'valid': False,
        'auth_file_exists': False,
        'can_access_favorites': False,
        'listings_found': 0,
        'needs_login': False,
        'error': None
    }

    # Check if auth.json exists
    if not os.path.exists(AUTH_JSON):
        result['needs_login'] = True
        result['error'] = 'auth.json not found - manual login required'
        return result

    result['auth_file_exists'] = True

    try:
        async with async_playwright() as p:
            # Launch headless browser with saved session
            browser = await p.chromium.launch(headless=True)
            context = await browser.new_context(storage_state=AUTH_JSON)
            page = await context.new_page()

            # Try to access favorites page
            try:
                await page.goto(FAVORITES_URL, timeout=30000)
                await page.wait_for_load_state("load", timeout=15000)
                result['can_access_favorites'] = True

                # Wait a moment for content to load
                await asyncio.sleep(2)

                # Check for login redirect or login form
                current_url = page.url
                if 'login' in current_url.lower() or 'signin' in current_url.lower():
                    result['needs_login'] = True
                    result['error'] = 'Session expired - redirected to login page'
                    await browser.close()
                    return result

                # Check if we can see favorite listings
                listings = await page.query_selector_all("article.item-adaptive.card-basic")
                result['listings_found'] = len(listings)

                if len(listings) > 0:
                    result['valid'] = True
                else:
                    # No listings might mean session expired OR empty favorites
                    # Check for "no favorites" message vs login prompt
                    login_form = await page.query_selector("form[action*='login']")
                    sign_in_button = await page.query_selector("a:has-text('Sign in'), a:has-text('Inloggen')")

                    if login_form or sign_in_button:
                        result['needs_login'] = True
                        result['error'] = 'Session expired - login form detected'
                    else:
                        # Probably just no favorites
                        result['valid'] = True
                        result['listings_found'] = 0

            except Exception as e:
                result['error'] = f'Failed to access favorites page: {str(e)}'

            await browser.close()

    except Exception as e:
        result['error'] = f'Browser error: {str(e)}'

    return result

async def invalidate_session():
    """
    Remove auth.json to force re-login
    """
    if os.path.exists(AUTH_JSON):
        # Backup first
        import shutil
        from datetime import datetime
        backup_name = f"auth_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        shutil.copy(AUTH_JSON, backup_name)
        os.remove(AUTH_JSON)
        return {
            'success': True,
            'message': f'Session invalidated. Backup saved to {backup_name}',
            'backup_file': backup_name
        }
    else:
        return {
            'success': False,
            'message': 'No auth.json found'
        }

if __name__ == "__main__":
    import json

    if len(sys.argv) > 1 and sys.argv[1] == 'invalidate':
        # Invalidate session
        result = asyncio.run(invalidate_session())
        print(json.dumps(result, indent=2))
    else:
        # Validate session
        result = asyncio.run(validate_session())

        # Print results
        print("=" * 70)
        print("PROPERSTAR SESSION VALIDATION")
        print("=" * 70)

        if result['valid']:
            print("✅ Session is VALID")
            print(f"   Favorites found: {result['listings_found']}")
        else:
            print("❌ Session is INVALID or EXPIRED")
            if result['error']:
                print(f"   Error: {result['error']}")
            if result['needs_login']:
                print("\n💡 Action required:")
                print("   1. Run: python3 validate_session.py invalidate")
                print("   2. Then run favorites scraper for manual login")

        print("\nDetails:")
        print(f"  auth.json exists: {result['auth_file_exists']}")
        print(f"  Can access favorites: {result['can_access_favorites']}")
        print(f"  Needs login: {result['needs_login']}")
        print("=" * 70)

        # Output JSON for programmatic use
        print("\nJSON Output:")
        print(json.dumps(result, indent=2))

        # Exit code
        sys.exit(0 if result['valid'] else 1)
