"""Simple local intent parser - no API key required."""

import re
from typing import Any

from .base import ActionPlan


class LocalIntentParser:
    """
    Simple rule-based intent parser.
    No API key required, works offline.
    """
    
    # Common URL patterns
    URL_PATTERNS = [
        r'(?:https?://)?(?:www\.)?([a-zA-Z0-9][-a-zA-Z0-9]*\.[a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z]{2,})?)',
    ]
    
    # Action keywords
    ACTION_PATTERNS = {
        'goto': [
            r'打开[了]?(?:网站)?\s*([a-zA-Z0-9][^\s,，。]*)',
            r'去[了]?\s*([a-zA-Z0-9][^\s,，。]*)',
            r'访问[了]?\s*([a-zA-Z0-9][^\s,，。]*)',
            r'go\s+to\s+([a-zA-Z0-9][^\s,]*)',
            r'open\s+([a-zA-Z0-9][^\s,]*)',
            r'visit\s+([a-zA-Z0-9][^\s,]*)',
        ],
        'screenshot': [
            r'截图',
            r'截屏',
            r'screenshot',
            r'take\s+a?\s*screenshot',
        ],
        'extract': [
            r'提取[了]?(?:所有)?(.+?)',
            r'获取[了]?(?:所有)?(.+?)',
            r'找到[了]?(?:所有)?(.+?)',
            r'查找[了]?(?:所有)?(.+?)',
            r'extract\s+(.+?)',
            r'find\s+(.+?)',
            r'get\s+(.+?)',
        ],
        'click': [
            r'点击[了]?(.+?)',
            r'按下[了]?(.+?)',
            r'click\s+(.+?)',
        ],
        'scroll': [
            r'滚动[到]?(.+?)',
            r'向下[滚动]?',
            r'scroll\s+(.+?)',
        ],
    }
    
    @classmethod
    def parse(cls, instruction: str) -> ActionPlan:
        """
        Parse natural language instruction into action plan.
        
        Args:
            instruction: Natural language instruction
            
        Returns:
            ActionPlan with list of actions
        """
        actions = []
        instruction_lower = instruction.lower()
        
        # Try to extract URL first
        url = cls._extract_url(instruction)
        
        # Check for screenshot
        if cls._match_any_pattern(instruction, cls.ACTION_PATTERNS['screenshot']):
            actions.append({"type": "screenshot", "path": "screenshot.png"})
        
        # Check for goto action
        goto_match = cls._match_any_pattern(instruction, cls.ACTION_PATTERNS['goto'])
        if goto_match:
            url = goto_match.group(1) if hasattr(goto_match, 'group') else url
            if url:
                # Add protocol if missing
                if not url.startswith(('http://', 'https://')):
                    url = 'https://' + url
                actions.append({"type": "goto", "url": url})
        elif url:
            # If no explicit goto but URL found, assume goto
            if not url.startswith(('http://', 'https://')):
                url = 'https://' + url
            actions.append({"type": "goto", "url": url})
        
        # Check for extract action
        extract_match = cls._match_any_pattern(instruction, cls.ACTION_PATTERNS['extract'])
        if extract_match:
            what = extract_match.group(1).strip() if hasattr(extract_match, 'group') else "text"
            selector = cls._what_to_selector(what)
            actions.append({"type": "extract", "selector": selector})
        
        # Check for click action
        click_match = cls._match_any_pattern(instruction, cls.ACTION_PATTERNS['click'])
        if click_match:
            target = click_match.group(1).strip() if hasattr(click_match, 'group') else "button"
            selector = cls._target_to_selector(target)
            actions.append({"type": "click", "selector": selector})
        
        # If no actions parsed, default to goto
        if not actions:
            # Try to use instruction as URL
            url = instruction.strip()
            if url:
                if not url.startswith(('http://', 'https://')):
                    url = 'https://' + url
                actions.append({"type": "goto", "url": url})
        
        return ActionPlan(actions)
    
    @classmethod
    def _extract_url(cls, text: str) -> str | None:
        """Extract URL from text."""
        for pattern in cls.URL_PATTERNS:
            match = re.search(pattern, text, re.IGNORECASE)
            if match:
                return match.group(0)
        return None
    
    @classmethod
    def _match_any_pattern(cls, text: str, patterns: list[str]) -> re.Match | None:
        """Try to match any of the given patterns."""
        for pattern in patterns:
            match = re.search(pattern, text, re.IGNORECASE)
            if match:
                return match
        return None
    
    @classmethod
    def _what_to_selector(cls, what: str) -> str:
        """Convert 'what to extract' to CSS selector."""
        what_lower = what.lower().strip()
        
        # Common mappings
        mappings = {
            'title': 'title',
            '标题': 'h1',
            '链接': 'a',
            'links': 'a',
            '图片': 'img',
            'images': 'img',
            '价格': '[class*="price"], [class*="Price"]',
            'price': '[class*="price"], [class*="Price"]',
            '文本': 'body',
            'text': 'body',
            '内容': 'article, main, .content, #content',
            'content': 'article, main, .content, #content',
        }
        
        for key, selector in mappings.items():
            if key in what_lower:
                return selector
        
        # Default to body
        return 'body'
    
    @classmethod
    def _target_to_selector(cls, target: str) -> str:
        """Convert click target to CSS selector."""
        target_lower = target.lower().strip()
        
        # Common mappings
        mappings = {
            '按钮': 'button',
            'button': 'button',
            '链接': 'a',
            'link': 'a',
            '提交': 'button[type="submit"], input[type="submit"]',
            'submit': 'button[type="submit"], input[type="submit"]',
        }
        
        for key, selector in mappings.items():
            if key in target_lower:
                return selector
        
        # Default to button
        return 'button'
