import re
from typing import Dict, List, Tuple
from dataclasses import dataclass

@dataclass
class GuidelineRule:
    category: str
    rule_type: str  # 'approve' or 'reject'
    keywords: List[str]
    phrases: List[str]
    weight: float

class GuidelinesParser:
    def __init__(self, guidelines_path: str):
        print(f"🔄 Loading guidelines from: {guidelines_path}")
        self.guidelines_path = guidelines_path
        self.approve_rules = []
        self.reject_rules = []
        self.evaluation_metrics = []
        self._parse_guidelines()
        print(f"   ✅ Loaded {len(self.approve_rules)} approval rules, {len(self.reject_rules)} rejection rules")

    def _parse_guidelines(self):
        with open(self.guidelines_path, 'r', encoding='utf-8') as f:
            content = f.read()

        print("   Parsing approval criteria...")
        # Parse approval criteria
        approve_section = self._extract_section(content, "✅ WHAT WE WANT TO BE")
        if not approve_section:
            approve_section = self._extract_section(content, "✅ WHAT WE WANT TO SEE")
        self._parse_approval_rules(approve_section)

        print("   Parsing rejection criteria...")
        # Parse rejection criteria
        reject_section = self._extract_section(content, "❌ WHAT WE DON'T WANT TO BE")
        if not reject_section:
            reject_section = self._extract_section(content, "❌ WHAT WE REJECT")
        self._parse_rejection_rules(reject_section)

        print("   Parsing evaluation metrics...")
        # Parse evaluation metrics
        metrics_section = self._extract_section(content, "📊 SPECIFIC METRICS TO EVALUATE")
        self._parse_evaluation_metrics(metrics_section)

    def _extract_section(self, content: str, section_header: str) -> str:
        pattern = rf"{re.escape(section_header)}(.*?)(?=\n[✅❌🎯📊]|\Z)"
        match = re.search(pattern, content, re.DOTALL)
        return match.group(1) if match else ""

    def _parse_approval_rules(self, section: str):
        categories = {
            "Core Positioning": ["music-first", "artist empowerment", "creativity", "imagination", "magic", "joy"],
            "Tone & Voice": ["optimistic", "playful", "experimental", "accessible", "inclusive", "authentic", "poetic"],
            "Audience Alignment": ["young creatives", "Gen Z", "community", "connection", "belonging", "social"],
            "Value Propositions": ["self-expression", "meaningful creativity", "education", "culture", "community"]
        }

        for category, keywords in categories.items():
            phrases = self._extract_phrases_from_section(section, category)
            self.approve_rules.append(GuidelineRule(
                category=category,
                rule_type='approve',
                keywords=keywords,
                phrases=phrases,
                weight=1.0
            ))

    def _parse_rejection_rules(self, section: str):
        categories = {
            "Problematic Positioning": ["AI-first", "tech-heavy", "replacing human artists", "AI music company"],
            "Wrong Tone": ["tech bro", "absolute claims", "salesy", "exclusive", "hyperbolic", "buzzword"],
            "Misaligned Messaging": ["features over value", "technology over artistry", "shortcut", "effortless"],
            "Perception Red Flags": ["cheap AI slop", "trivializes", "bypass learning", "transactional"]
        }

        for category, keywords in categories.items():
            phrases = self._extract_phrases_from_section(section, category)
            self.reject_rules.append(GuidelineRule(
                category=category,
                rule_type='reject',
                keywords=keywords,
                phrases=phrases,
                weight=1.0
            ))

    def _parse_evaluation_metrics(self, section: str):
        lines = section.strip().split('\n')
        for line in lines:
            if line.strip() and line.strip().startswith('Does it'):
                self.evaluation_metrics.append(line.strip())

    def _extract_phrases_from_section(self, section: str, category: str) -> List[str]:
        lines = section.split('\n')
        in_category = False
        phrases = []

        for line in lines:
            line = line.strip()
            if category in line:
                in_category = True
                continue
            elif line and not line[0].islower() and in_category:
                in_category = False
            elif in_category and line:
                phrases.append(line)

        return phrases

    def get_approval_rules(self) -> List[GuidelineRule]:
        return self.approve_rules

    def get_rejection_rules(self) -> List[GuidelineRule]:
        return self.reject_rules

    def get_evaluation_metrics(self) -> List[str]:
        return self.evaluation_metrics