import re
from typing import Optional, Any
from dataclasses import dataclass

@dataclass
class PatternMatch:
    pattern_type: str          # "cheaper_than", "similar_to", "check_size", ...
    reference_sku: Optional[str] = None
    reference_product_line: Optional[str] = None
    reference_price: Optional[float] = None
    reference_color: Optional[str] = None
    reference_size: Optional[str] = None
    target_price_max: Optional[float] = None
    target_price_min: Optional[float] = None
    target_size: Optional[str] = None
    target_color: Optional[str] = None
    confidence: float = 0.0
    raw_match: str = ""

class HardPatternDetector:
    CHEAPER_PATTERNS = [r"(?:rẻ|giá)\s+(?:hơn|thấp hơn|xuống hơn)", r"có.*rẻ.*hơn"]
    EXPENSIVE_PATTERNS = [r"(?:đắt|giá)\s+(?:hơn|cao hơn)", r"có.*đắt.*hơn"]
    SIMILAR_PATTERNS = [r"(?:giống|tương tự|như|cùng)\s+(?:như|với)?\s+(?:cái|chiếc)?\s*(?:đó|trước|ban\s*nãy|cạnh|là)?"]
    SIZE_CHECK_PATTERNS = [r"(?:còn|có)\s+size\s+([A-Z0-9]+)"]
    COLOR_CHECK_PATTERNS = [r"(?:màu\s+)?(\w+)\s+(?:còn|có)"]
    STOCK_CHECK_PATTERNS = [r"(?:còn|có)\s+(?:hàng|kho)\s+(?:không|ko|kh)"]
    SKU_PATTERN = r"\b([A-Z0-9]{4,}-[A-Z0-9]{3,}(?:-[A-Z0-9]{3,})?)\b"

    def detect(self, query: str, context_products: list[dict] = None) -> PatternMatch:
        query_lower = query.lower().strip()
        match = PatternMatch(pattern_type="unknown")

        if any(re.search(p, query_lower) for p in self.CHEAPER_PATTERNS):
            match.pattern_type = "cheaper_than"
            match.confidence = 0.9
        elif any(re.search(p, query_lower) for p in self.EXPENSIVE_PATTERNS):
            match.pattern_type = "more_expensive_than"
            match.confidence = 0.9
        elif any(re.search(p, query_lower) for p in self.SIMILAR_PATTERNS):
            match.pattern_type = "similar_to"
            match.confidence = 0.8
        elif sm := re.search(self.SIZE_CHECK_PATTERNS[0], query_lower):
            match.pattern_type = "check_size"
            match.target_size = sm.group(1).upper()
        
        # Populate reference info if available
        if context_products and match.pattern_type != "unknown":
            last_p = context_products[-1]
            match.reference_sku = last_p.get("code") or last_p.get("magento_ref_code")
            match.reference_price = float(last_p.get("price") or 0)
            match.reference_product_line = last_p.get("product_line_vn")
            
            if match.pattern_type == "cheaper_than":
                match.target_price_max = match.reference_price * 0.95
            elif match.pattern_type == "more_expensive_than":
                match.target_price_min = match.reference_price * 1.05

        return match
