#!/usr/bin/env python3
"""
Archive Check Plugin

Checks if a URL is archived on archive.is.
"""

import asyncio
import random
from typing import Dict, Any
from lib.plugin_loader import PluginMetadata, PluginParameter
from lib.primitive.click_element import ClickElement
from lib.primitive.type_text import TypeText
from lib.primitive.paste_text import PasteText
from lib.primitive.press_enter import PressEnter


class ArchiveCheckPlugin:
    """
    Check if a URL is archived on archive.is.
    
    Supports two modes:
    - Direct navigation: Go directly to archive.is/<url>
    - Search form: Navigate to archive.is, use search form
    """
    
    metadata = PluginMetadata(
        name="archive-check",
        description="Archive Check",
        methods=["POST"],
        bg_color=["#c2601f", "#ff9924"],
        parameters=[
            PluginParameter(
                name="url",
                type="url",
                label="URL to Check",
                required=True,
                placeholder="https://example.com",
                help_text="URL to check for archived copies on archive.is"
            ),
            PluginParameter(
                name="direct_nav_probability",
                type="number",
                label="Direct Navigation Probability",
                required=False,
                default=0.5,
                help_text="Probability (0.0-1.0) of directly navigating to archive.is/<url> vs using search form"
            ),
            PluginParameter(
                name="paste_probability",
                type="number",
                label="Paste Probability",
                required=False,
                default=0.9,
                help_text="Probability (0.0-1.0) of pasting vs typing the URL"
            )
        ]
    )
    
    def validate_params(self, params: Dict[str, Any]) -> str | None:
        """Custom validation for probability parameters."""
        direct_prob = params.get('direct_nav_probability', 0.5)
        paste_prob = params.get('paste_probability', 0.9)
        
        if not (0.0 <= direct_prob <= 1.0):
            return "direct_nav_probability must be between 0.0 and 1.0"
        if not (0.0 <= paste_prob <= 1.0):
            return "paste_probability must be between 0.0 and 1.0"
        
        return None
    
    async def execute(self, browser_navigator, page_id: str, params: Dict[str, Any]) -> Dict[str, Any]:
        """
        Execute archive check operation.
        
        Args:
            browser_navigator: BrowserNavigator instance
            page_id: Page to use for operation
            params: Validated parameters (url, direct_nav_probability, paste_probability)
            
        Returns:
            Dict with success status, is_archived flag, and method used
        """
        url = params['url']
        direct_nav_probability = params.get('direct_nav_probability', 0.5)
        paste_probability = params.get('paste_probability', 0.9)
        
        print(f"🔍 Archive check: url={url}, direct_prob={direct_nav_probability}, paste_prob={paste_probability}")
        
        managed_page = await browser_navigator._get_page_to_use(page_id)
        page = managed_page.page
        
        try:
            await managed_page.set_busy(f"checking archive for {url}")
            
            # Initialize primitives
            clicker = ClickElement()
            typer = TypeText()
            paster = PasteText()
            presser = PressEnter()
            
            # Randomly decide: direct navigation or search form
            use_direct_nav = random.random() < direct_nav_probability
            
            if use_direct_nav:
                # Direct navigation to archive.is/<url>
                print(f"🎯 Direct navigation to archive.is/{url}")
                archive_url = f"https://archive.is/{url}"
                await page.goto(archive_url, wait_until='domcontentloaded')
                await asyncio.sleep(2)
            else:
                # Search form approach
                print("🔍 Using search form approach")
                
                # Navigate to archive.is
                print("🌐 Navigating to archive.is...")
                await page.goto('https://archive.is', wait_until='domcontentloaded')
                await asyncio.sleep(1)
                
                # Click search input
                print("👆 Clicking search input...")
                click_result = await clicker.click_selector(managed_page, '#q')
                if not click_result.get('success'):
                    return {
                        "success": False,
                        "url": url,
                        "error": f"Failed to click input: {click_result.get('error')}"
                    }
                
                # Type or paste URL
                print(f"⌨️ Entering URL: {url}")
                if random.random() < paste_probability:
                    type_result = await paster.paste(page, url)
                else:
                    type_result = await typer.type(page, url)
                
                if not type_result.get('success'):
                    return {
                        "success": False,
                        "url": url,
                        "error": f"Failed to enter URL: {type_result.get('error')}"
                    }
                
                # Press enter to search
                print("⏎ Pressing Enter to search...")
                press_result = await presser.press(page)
                if not press_result.get('success'):
                    return {
                        "success": False,
                        "url": url,
                        "error": f"Failed to press Enter: {press_result.get('error')}"
                    }
                
                # Wait for navigation/results
                await asyncio.sleep(2)
            
            # Check page content for archive status
            content = await page.content()
            
            is_archived1 = "No results" not in content
            is_archived2 = "You may want to" not in content
            is_archived3 = "List of URLs, ordered from newer to older" in content
            
            result = {
                "success": True,
                "url": url,
                "page_id": managed_page.page_id,
                "is_archived": all([is_archived1, is_archived2, is_archived3]),
                "wtf": any([not is_archived1, not is_archived2, not is_archived3]),
                "method": "direct_nav" if use_direct_nav else "search_form"
            }
            
            print(f"✅ Archive check completed: is_archived={result['is_archived']}")
            return result
        
        except Exception as e:
            print(f"❌ Archive check failed: {e}")
            await managed_page.set_error(str(e))
            raise
        
        finally:
            await managed_page.set_idle()
