"""
Reporter — iki farklı output:
  ConsoleReporter → renkli terminal çıktısı (insan okur)
  AIReporter      → yapılandırılmış JSON/MD (AI okur)
"""

import json

try:
    from ..rules.validator import Violation
except ImportError:
    from validator import Violation

SEVERITY_ICON = {
    "error": "X",
    "warning": "!",
    "info": ">",
}

SEVERITY_ORDER = {"error": 0, "warning": 1, "info": 2}


class ConsoleReporter:
    def report(self, violations: list[Violation], context: str = ""):
        if not violations:
            print(f"\033[92m[aicontract] ✓ {context} — kural ihlali yok\033[0m")
            return

        if context:
            print(f"\n\033[1m[aicontract] {context}\033[0m")

        sorted_v = sorted(violations, key=lambda v: SEVERITY_ORDER.get(v.severity, 9))

        for v in sorted_v:
            icon = SEVERITY_ICON.get(v.severity, "?")
            conf = f"{int(v.confidence * 100)}%"

            if v.severity == "error":
                color = "\033[91m"
            elif v.severity == "warning":
                color = "\033[93m"
            else:
                color = "\033[94m"

            print(f"{color}{icon} [{v.rule_id}] {v.message}\033[0m")
            print(f"   Konum    : {v.location}")
            print(f"   Güven    : {conf}")
            print(f"   Öneri    : {v.suggestion}")
            print()

    def summary(self, all_violations: list[Violation], scanned_files: int = 0):
        errors = [v for v in all_violations if v.severity == "error"]
        warnings = [v for v in all_violations if v.severity == "warning"]
        infos = [v for v in all_violations if v.severity == "info"]

        print("-" * 50)
        print("[aicontract] Tarama tamamlandı")
        if scanned_files:
            print(f"  Dosya     : {scanned_files}")
        print(f"  \033[91mHata      : {len(errors)}\033[0m")
        print(f"  \033[93mUyarı     : {len(warnings)}\033[0m")
        print(f"  \033[94mBilgi     : {len(infos)}\033[0m")

        try:
            from ..rules.validator import calculate_suspicion_score
        except ImportError:
            from validator import calculate_suspicion_score

        suspicion = calculate_suspicion_score(all_violations)

        print("-" * 50)
        if suspicion["level"] == "danger":
            print(f"  {suspicion['message']}")
            print(f"  [SKOR: {suspicion['total']}] Ciddi sorunlar var!")
        elif suspicion["level"] == "warning":
            print(f"  {suspicion['message']}")
            print(f"  [SKOR: {suspicion['total']}] Dikkatli ol.")
        elif suspicion["level"] == "caution":
            print(f"  {suspicion['message']}")
            print(f"  [SKOR: {suspicion['total']}]")
        else:
            print("\033[92m  Proje anayasasına uygun. ✓\033[0m")

        print("-" * 50)


class AIReporter:
    """
    AI'ın prompt context'ine inject edeceği format.
    İki mod: json (makine), markdown (prompt injection).
    """

    def to_json(self, violations: list[Violation], registry=None) -> str:
        data = {
            "violations": [self._violation_dict(v) for v in violations],
            "summary": {
                "total": len(violations),
                "errors": len([v for v in violations if v.severity == "error"]),
                "warnings": len([v for v in violations if v.severity == "warning"]),
                "infos": len([v for v in violations if v.severity == "info"]),
            },
        }
        if registry:
            data["registry_snapshot"] = {
                "function_count": len(registry.functions),
                "domain_count": len(registry.domains),
                "empty_domains": [d.name for d in registry.empty_domains()],
                "high_risk": [f.name for f in registry.high_risk_functions()],
            }
        return json.dumps(data, indent=2, ensure_ascii=False)

    def to_markdown(self, violations: list[Violation], registry=None) -> str:
        lines = ["# aicontract — Proje Durum Raporu\n"]

        if registry:
            lines.append("## Proje Özeti")
            lines.append(f"- Kayıtlı fonksiyon: {len(registry.functions)}")
            lines.append(f"- Domain sayısı: {len(registry.domains)}")
            empty = registry.empty_domains()
            if empty:
                names = ", ".join(d.name for d in empty)
                lines.append(f"- Sahipsiz domainler: {names}")
            high = registry.high_risk_functions()
            if high:
                names = ", ".join(f.name for f in high)
                lines.append(f"- Yüksek riskli fonksiyonlar: {names}")
            lines.append("")

        if not violations:
            lines.append("## Sonuç\nProje anayasasına uygun. Kural ihlali yok.")
            return "\n".join(lines)

        errors = [v for v in violations if v.severity == "error"]
        warnings = [v for v in violations if v.severity == "warning"]
        infos = [v for v in violations if v.severity == "info"]

        if errors:
            lines.append("## Hatalar (düzeltilmeli)")
            for v in errors:
                lines.append(f"- **[{v.rule_id}]** `{v.func_name or '?'}`: {v.message}")
                lines.append(f"  - Öneri: {v.suggestion}")
            lines.append("")

        if warnings:
            lines.append("## Uyarılar")
            for v in warnings:
                lines.append(f"- **[{v.rule_id}]** `{v.func_name or '?'}`: {v.message}")
                lines.append(f"  - Öneri: {v.suggestion}")
            lines.append("")

        if infos:
            lines.append("## Bilgiler")
            for v in infos:
                lines.append(f"- **[{v.rule_id}]** {v.message}")
                lines.append(f"  - Öneri: {v.suggestion}")

        return "\n".join(lines)

    def _violation_dict(self, v: Violation) -> dict:
        return {
            "rule_id": v.rule_id,
            "severity": v.severity,
            "confidence": v.confidence,
            "message": v.message,
            "location": v.location,
            "suggestion": v.suggestion,
            "func_name": v.func_name,
        }
