"""
Pattern definitions for AI writing detection.

Each pattern has: name, regex, weight, severity, description, suggestion.
Based on Wikipedia's "Signs of AI writing" guide.
"""

import re
from dataclasses import dataclass, field
from typing import List, Dict, Optional


@dataclass
class Pattern:
    """A single AI writing pattern detector."""
    name: str
    regex: str
    weight: float
    severity: str  # low, medium, high, critical
    description: str
    suggestion: str
    examples: List[str] = field(default_factory=list)
    _compiled: Optional[re.Pattern] = field(default=None, repr=False)

    def compile(self) -> re.Pattern:
        """Compile regex pattern (cached)."""
        if self._compiled is None:
            self._compiled = re.compile(self.regex, re.IGNORECASE | re.MULTILINE)
        return self._compiled

    def findall(self, text: str) -> List[str]:
        """Find all matches in text."""
        return self.compile().findall(text)

    def count(self, text: str) -> int:
        """Count matches in text."""
        return len(self.findall(text))


# ─── English AI Writing Patterns ───────────────────────────────────────────

ENGLISH_PATTERNS = [
    Pattern(
        name="em_dash",
        regex=r"—",
        weight=1.0,
        severity="low",
        description="Em-dash (—) appears frequently. Uncommon in casual writing, overused by AI.",
        suggestion='Replace "—" with ", " or ". " or use regular hyphen "-".',
        examples=["This is important — very important indeed."]
    ),
    Pattern(
        name="ai_vocabulary",
        regex=r"\b(crucial|pivotal|tapestry|underscore|delve|landscape|testament|vibrant|intricate|poignant|seamless|comprehensive|robust|foster|garner|emphasize|highlight|nuance|multifaceted|leverage|paradigm|synergy|holistic)\b",
        weight=1.0,
        severity="medium",
        description="Hallmark AI vocabulary words that appear disproportionately in generated text.",
        suggestion='Use simpler alternatives: "crucial"→"important", "tapestry"→"mix", "delve"→"look into".',
        examples=["It is crucial to delve into this multifaceted landscape."]
    ),
    Pattern(
        name="rule_of_three",
        regex=r"\b\w{3,},\s+\w{3,},\s+and\s+\w{3,}\b",
        weight=0.5,
        severity="low",
        description='Three-item list structure "A, B, and C" — AI overuses this pattern.',
        suggestion="Vary your list structures. Use two items, four items, or restructure entirely.",
        examples=["Comprehensive, robust, and seamless integration."]
    ),
    Pattern(
        name="negative_parallelism",
        regex=r"(?i)(it'?s?\s+not\s+(?:just|merely|only|simply)\s+\w+(?:\s+\w+){0,3}(?:,|—|;\s*it'?s?)\s+(?:it'?s?\s+)?)",
        weight=2.0,
        severity="high",
        description="Negative parallelism structure: 'It's not X, it's Y' — extremely common in AI text.",
        suggestion="Express the idea directly without the 'not just X, but Y' framing.",
        examples=["It's not just a tool, it's a revolution."]
    ),
    Pattern(
        name="boast_language",
        regex=r"(?i)\b(boasts?\s+(?:an?\s+)?\w+|stands?\s+as\s+(?:a\s+)?(?:testament|monument|beacon)|serves?\s+as\s+(?:a\s+)?(?:cornerstone|pillar|testament)|represents?\s+(?:a\s+)?(?:significant|major|pivotal|testament))\b",
        weight=2.0,
        severity="high",
        description="Promotional/boastful framing that AI uses to describe things positively.",
        suggestion="State facts plainly. Instead of 'boasts 500 stars', say 'has 500 stars'.",
        examples=["This project stands as a testament to innovation."]
    ),
    Pattern(
        name="promotional",
        regex=r"(?i)\b(groundbreaking|cutting.edge|state.of.the.art|game.changer|revolutionary|breathtaking|stunning|unprecedented|unparalleled|transformative|disruptive|innovative\s+(?:solution|approach))\b",
        weight=2.0,
        severity="high",
        description="Promotional buzzwords that signal AI-generated marketing content.",
        suggestion="Use specific, concrete descriptions instead of buzzwords.",
        examples=["This groundbreaking tool represents a revolutionary approach."]
    ),
    Pattern(
        name="vague_attribution",
        regex=r"(?i)\b(industry\s+experts\s+(?:say|believe|agree)|observers\s+(?:note|suggest|point)|critics\s+(?:argue|contend|suggest)|some\s+(?:argue|say|believe|suggest)|many\s+(?:believe|argue|contend|suggest)|it\s+is\s+widely\s+(?:believed|accepted|recognized|acknowledged)|research\s+(?:shows|suggests|indicates|demonstrates)\s+that)\b",
        weight=2.0,
        severity="high",
        description="Vague attributions without specific sources — AI creates fake authority.",
        suggestion="Cite specific sources: 'According to Smith (2024)...', or remove the claim.",
        examples=["Industry experts say this represents a paradigm shift."]
    ),
    Pattern(
        name="collaborative_artifact",
        regex=r"(?i)\b(I\s+hope\s+this\s+helps|let\s+me\s+know\s+if|would\s+you\s+like\s+(?:me\s+)?to|of\s+course!|certainly!|absolutely!|I'?d\s+be\s+(?:happy|glad|pleased)\s+to\s+help|is\s+there\s+anything\s+else|feel\s+free\s+to\s+ask)\b",
        weight=3.0,
        severity="critical",
        description="Chatbot conversation artifacts left in the text — definitive AI sign.",
        suggestion="Remove these phrases entirely. They're conversation markers, not content.",
        examples=["I hope this helps! Let me know if you have any questions."]
    ),
    Pattern(
        name="filler_phrase",
        regex=r"(?i)\b(in\s+order\s+to|due\s+to\s+the\s+fact\s+that|at\s+this\s+point\s+in\s+time|it\s+is\s+(?:important|worth|essential)\s+to\s+note\s+that|it'?s?\s+worth\s+(?:noting|mentioning|pointing\s+out)|without\s+(?:a\s+)?doubt|needless\s+to\s+say|last\s+but\s+not\s+least)\b",
        weight=1.0,
        severity="medium",
        description="Academic/formal filler phrases that AI overuses.",
        suggestion="Cut these phrases. Start directly with the main point.",
        examples=["It is important to note that this represents a significant advancement."]
    ),
    Pattern(
        name="ing_superficial",
        regex=r"\w+ing,\s+(ensuring|reflecting|highlighting|underscoring|emphasizing|demonstrating|illustrating|showcasing)",
        weight=2.0,
        severity="high",
        description="Superficial -ing clause pattern: 'doing X, reflecting Y' — AI analysis shortcut.",
        suggestion="Replace with direct statements. Instead of 'X happened, reflecting Y', say 'X happened because Y'.",
        examples=["The system processes data efficiently, ensuring optimal performance."]
    ),
    Pattern(
        name="negative_conclusion",
        regex=r"(?i)(despite\s+(?:these\s+|the\s+|some\s+)?\w*\s*challenges?|faces?\s+several\s+challenges?|moving\s+forward|looking\s+ahead|going\s+forward|as\s+we\s+(?:move|look)\s+(?:forward|ahead))",
        weight=1.0,
        severity="medium",
        description="Negative conclusion framing that AI uses to sound balanced.",
        suggestion="Be specific about challenges instead of generic 'despite challenges'.",
        examples=["Despite these challenges, the future looks promising."]
    ),
    Pattern(
        name="hedging",
        regex=r"(?i)\b(it\s+(?:seems|appears)\s+(?:that|to\s+be)|arguably|one\s+might\s+(?:say|argue|suggest)|it\s+could\s+be\s+(?:said|argued)\s+that|in\s+(?:many|some)\s+(?:ways|respects)|to\s+(?:some|a\s+(?:certain|large))\s+extent)\b",
        weight=1.0,
        severity="medium",
        description="Excessive hedging — AI tries to sound balanced by qualifying everything.",
        suggestion="Be direct. Instead of 'it seems that', state your point.",
        examples=["It seems that this approach could potentially be effective."]
    ),
    Pattern(
        name="conclusion_transition",
        regex=r"(?i)\b(in\s+conclusion|to\s+sum\s+up|in\s+summary|wrapping\s+up|to\s+(?:recap|recapitulate)|all\s+in\s+all|in\s+(?:the\s+)?final\s+analysis)\b",
        weight=1.5,
        severity="medium",
        description="Formulaic conclusion transitions that AI relies on.",
        suggestion="End naturally without formulaic transitions, or use a specific summary point.",
        examples=["In conclusion, this represents a significant step forward."]
    ),
    Pattern(
        name="conjunctive_adverb_overuse",
        regex=r"(?i)\b(furthermore|moreover|additionally|consequently|nevertheless|nonetheless|notwithstanding|whereas|hereby|thereof|therein|wherein)\b",
        weight=1.5,
        severity="medium",
        description="Formal conjunctive adverbs overused by AI to sound academic.",
        suggestion="Use 'also', 'but', 'so' instead of 'furthermore', 'nevertheless'.",
        examples=["Furthermore, it is worth noting that the system demonstrates robust capabilities."]
    ),
    Pattern(
        name="universal_claim",
        regex=r"(?i)\b(everyone\s+(?:knows|agrees|understands)|no\s+one\s+(?:can\s+)?deny|it'?s?\s+universally\s+(?:accepted|acknowledged)|we\s+all\s+(?:know|agree|understand)|across\s+the\s+(?:board|globe|world))\b",
        weight=2.0,
        severity="high",
        description="Universal generalizations that AI uses to establish 'common knowledge'.",
        suggestion="Qualify your claims. Instead of 'everyone knows', say 'many people find that...'.",
        examples=["Everyone knows that AI is transforming every industry."]
    ),
    Pattern(
        name="numbered_benefits",
        regex=r"(?i)(?:three|3|four|4|five|5)\s+(?:key|main|primary|major|significant)\s+(?:benefits|advantages|reasons|factors|ways)",
        weight=1.5,
        severity="medium",
        description="Numbered benefit/reason framing — classic AI listicle pattern.",
        suggestion="Introduce benefits naturally within the narrative instead of announcing the count.",
        examples=["There are three key benefits to this approach."]
    ),
]


# ─── Chinese AI Writing Patterns ───────────────────────────────────────────

CHINESE_PATTERNS = [
    Pattern(
        name="cn_boast",
        regex=r"(?:具有|拥有|具备)(?:重大|深远|显著|巨大)(?:的)?(?:意义|价值|影响|作用)",
        weight=2.0,
        severity="high",
        description="中文AI常用的夸大表述",
        suggestion="用具体数据或事实替代形容词堆砌",
        examples=["该项目具有重大的意义"]
    ),
    Pattern(
        name="cn_filler",
        regex=r"(?:值得注意的是|需要指出的是|不可否认|毋庸置疑|毫无疑问|可以说|可以认为|总的来说|综上所述)",
        weight=1.5,
        severity="medium",
        description="中文AI常用的填充短语",
        suggestion="直接说重点，去掉这些过渡语",
        examples=["值得注意的是，这一创新具有深远影响"]
    ),
    Pattern(
        name="cn_parallelism",
        regex=r"(?:不仅|不仅仅?)(?:是)?\s*\w+\s*(?:，|,)\s*(?:更|还|而且|也)(?:是)?\s*\w+",
        weight=2.0,
        severity="high",
        description="中文AI的排比结构：不仅是X，更是Y",
        suggestion="直接表达核心观点，避免排比句式",
        examples=["这不仅是一个工具，更是一种全新的思维方式"]
    ),
    Pattern(
        name="cn_vocabulary",
        regex=r"(?:赋能|抓手|闭环|打法|对齐|颗粒度|组合拳|底层逻辑|顶层设计|生态化|场景化|智能化)",
        weight=1.0,
        severity="medium",
        description="互联网黑话/行话，AI过度使用",
        suggestion="用通俗易懂的表达替代行话",
        examples=["通过数据赋能实现业务闭环"]
    ),
    Pattern(
        name="cn_promotional",
        regex=r"(?:颠覆性|革命性|突破性|开创性|划时代|前所未有的|无与伦比的|卓越的|顶尖的|领先的)",
        weight=2.0,
        severity="high",
        description="中文AI的宣传性词汇",
        suggestion="用具体功能和效果描述替代形容词",
        examples=["这款颠覆性产品开创了行业先河"]
    ),
]


# ─── Registry ───────────────────────────────────────────────────────────────

PATTERN_REGISTRY = {
    "en": ENGLISH_PATTERNS,
    "zh": CHINESE_PATTERNS,
    "all": ENGLISH_PATTERNS + CHINESE_PATTERNS,
}


def get_patterns(language: str = "all") -> List[Pattern]:
    """Get pattern list for a language."""
    return PATTERN_REGISTRY.get(language, PATTERN_REGISTRY["all"]).copy()


def load_custom_patterns(yaml_path: str) -> List[Pattern]:
    """Load custom patterns from a YAML config file."""
    import yaml
    with open(yaml_path, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f)

    patterns = []
    for name, spec in config.get("patterns", {}).items():
        patterns.append(Pattern(
            name=name,
            regex=spec["regex"],
            weight=spec.get("weight", 1.0),
            severity=spec.get("severity", "medium"),
            description=spec.get("description", f"Custom pattern: {name}"),
            suggestion=spec.get("suggestion", "Review and revise."),
        ))
    return patterns
