"""
Plugin Sistemi - MVP

Kullanıcılar kendi kurallarını tanımlayabilir.
aicontract.yaml içinde:

plugins:
  - name: my_custom_rule
    pattern: "TODO|FIXME|XXX"
    severity: warning
    message: "Unresolved marker"
"""

import re
from pathlib import Path
from dataclasses import dataclass


@dataclass
class PluginRule:
    name: str
    pattern: str
    severity: str = "warning"
    message: str = ""
    enabled: bool = True


class PluginRegistry:
    """Plugin kurallarını yönetir."""

    def __init__(self):
        self.rules: list[PluginRule] = []

    def register(self, rule: PluginRule):
        """Yeni kural ekle."""
        self.rules.append(rule)

    def load_from_yaml(self, yaml_path: str):
        """YAML'den kuralları yükle."""
        import yaml

        path = Path(yaml_path)
        if not path.exists():
            return

        with open(path) as f:
            data = yaml.safe_load(f)

        plugins = data.get("plugins", [])
        for p in plugins:
            rule = PluginRule(
                name=p.get("name", "unnamed"),
                pattern=p.get("pattern", ""),
                severity=p.get("severity", "warning"),
                message=p.get("message", "Custom rule violation"),
                enabled=p.get("enabled", True),
            )
            if rule.pattern:
                self.register(rule)

    def get_active_rules(self) -> list[PluginRule]:
        """Aktif kuralları döndür."""
        return [r for r in self.rules if r.enabled]

    def apply(self, source: str, filepath: str = "") -> list[dict]:
        """Tüm aktif kuralları uygula."""
        violations = []

        for rule in self.get_active_rules():
            try:
                matches = re.finditer(rule.pattern, source, re.IGNORECASE)
                for match in matches:
                    violations.append(
                        {
                            "rule": rule.name,
                            "severity": rule.severity,
                            "message": rule.message or f"{rule.name} matched",
                            "file": filepath,
                            "match": match.group(),
                            "line": source[: match.start()].count("\n") + 1,
                        }
                    )
            except re.error:
                continue

        return violations


# Global plugin registry
_global_registry = PluginRegistry()


def load_plugins(config_path: str = "aicontract.yaml"):
    """Plugin'leri yükle."""
    _global_registry.load_from_yaml(config_path)
    return _global_registry


def get_plugin_violations(source: str, filepath: str = "") -> list[dict]:
    """Plugin violation'larını getir."""
    return _global_registry.apply(source, filepath)


# Örnek kullanım
if __name__ == "__main__":
    # Test
    registry = PluginRegistry()
    registry.register(
        PluginRule(
            name="todo_check",
            pattern=r"\bTODO\b|\bFIXME\b|\bXXX\b",
            severity="info",
            message="Unresolved marker found",
        )
    )

    test_code = """
def old_function():
    # TODO: refactor this
    return True
    """

    violations = registry.apply(test_code, "test.py")
    print("Violations:", violations)
