"""Brand consistency checker for content validation."""

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional

from ..utils.logger import Logger

if TYPE_CHECKING:
    from .api_client import ApiClient


@dataclass
class BrandCheckResult:
    """Result of brand consistency check."""

    passed: bool
    status: str  # "pass", "fail", "warning"
    score: float  # 0-100
    issues: list[dict]
    suggestions: list[str]


class BrandChecker:
    """Checks content against Reply Cash brand guidelines."""

    # Reply Cash brand guidelines
    BRAND_GUIDELINES = """
## Reply Cash Brand Guidelines

### Tone of Voice
- Professional but approachable
- Confident, not arrogant
- Empathetic to financial struggles
- Excited about the solution

### Key Messaging
- Focus on: low fees, speed, simplicity, accessibility
- Target: senders (crypto holders, diaspora) and recipients (families)
- Value prop: stablecoin to mobile money instantly

### Terms to Use
✓ "stablecoins" (USDC, USDT)
✓ "mobile money"
✓ "instant conversion"
✓ "low fees"
✓ "no bank account needed"

### Terms to Avoid
✗ "crypto" (use "stablecoins" instead)
✗ "blockchain" (too technical)
✗ "wallet" (confusing with mobile money)
✗ "decentralized" (too technical)

### Content Structure
- Lead with benefits, not features
- Use "so that" framing
- Short paragraphs (2-3 lines max)
- Clear CTAs
"""

    def __init__(self, api_client: Optional["ApiClient"] = None) -> None:
        self.api_client = api_client

    def check_content(
        self, content: str, content_type: str = "blog", use_api: bool = True
    ) -> BrandCheckResult:
        """Check content against brand guidelines.

        Args:
            content: The content to check
            content_type: Type of content (blog, social, email, etc.)
            use_api: Whether to use the API for checking

        Returns:
            BrandCheckResult with status and issues
        """
        Logger.info("Checking brand consistency", {"type": content_type})

        # Use API if available
        if use_api and self.api_client:
            return self._check_via_api(content, content_type)

        # Local check
        return self._check_locally(content, content_type)

    def _check_via_api(self, content: str, content_type: str) -> BrandCheckResult:
        """Check content via brand consistency API."""
        try:
            response = self.api_client.post(
                "/skills/brand/check",
                {"content": {"type": content_type, "text": content}},
            )

            if response.success and response.data:
                data = response.data
                status = data.get("status", "unknown")
                # Both "pass" and "warning" are considered passed
                passed = status in ("pass", "warning")
                return BrandCheckResult(
                    passed=passed,
                    status=status,
                    score=data.get("score", 0),
                    issues=data.get("issues", []),
                    suggestions=data.get("suggestions", []),
                )

            # Fallback to local check
            return self._check_locally(content, content_type)

        except Exception as e:
            Logger.error("Brand check API failed", e)
            return self._check_locally(content, content_type)

    def _check_locally(self, content: str, content_type: str) -> BrandCheckResult:
        """Check content locally using brand guidelines."""
        issues = []
        suggestions = []
        score = 100

        content_lower = content.lower()

        # Check for terms to avoid
        terms_to_avoid = {
            "crypto": "Use 'stablecoins' instead of 'crypto'",
            "blockchain": "Avoid technical terms like 'blockchain'",
            "wallet": "Use 'mobile money' or 'account' instead of 'wallet'",
            "decentralized": "Avoid technical jargon like 'decentralized'",
        }

        for term, suggestion in terms_to_avoid.items():
            if term in content_lower:
                issues.append({
                    "type": "term",
                    "severity": "warning",
                    "message": f"Found term to avoid: '{term}'",
                    "suggestion": suggestion,
                })
                suggestions.append(suggestion)
                score -= 5

        # Check for key messaging
        key_terms = ["stablecoin", "mobile money", "instant", "low fee"]
        found_key_terms = sum(1 for term in key_terms if term in content_lower)

        if found_key_terms < 2:
            issues.append({
                "type": "messaging",
                "severity": "warning",
                "message": "Content missing key messaging",
                "suggestion": f"Include more key terms: {', '.join(key_terms)}",
            })
            suggestions.append(f"Consider adding key messaging: {', '.join(key_terms)}")
            score -= 10

        # Check paragraph length
        paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()]
        long_paragraphs = [p for p in paragraphs if len(p) > 300]

        if long_paragraphs:
            issues.append({
                "type": "formatting",
                "severity": "info",
                "message": f"{len(long_paragraphs)} paragraph(s) are too long",
                "suggestion": "Break paragraphs into 2-3 lines for readability",
            })
            suggestions.append("Break long paragraphs into shorter ones")
            score -= 3

        # Check for CTA
        cta_keywords = ["sign up", "get started", "try", "join", "learn more"]
        has_cta = any(cta in content_lower for cta in cta_keywords)

        if not has_cta:
            issues.append({
                "type": "cta",
                "severity": "warning",
                "message": "No clear call-to-action found",
                "suggestion": "Add a clear CTA like 'Get Started' or 'Learn More'",
            })
            suggestions.append("Add a clear call-to-action")
            score -= 5

        # Determine status
        if score >= 90:
            status = "pass"
        elif score >= 70:
            status = "warning"
        else:
            status = "fail"

        return BrandCheckResult(
            passed=status in ("pass", "warning"),
            status=status,
            score=max(0, score),
            issues=issues,
            suggestions=suggestions,
        )

    def format_result(self, result: BrandCheckResult) -> str:
        """Format check result for display."""
        lines = []

        # Status icon
        icon = "✅" if result.status == "pass" else "⚠️" if result.status == "warning" else "❌"
        lines.append(f"{icon} Brand Check: {result.status.upper()} (Score: {result.score}/100)")
        lines.append("")

        if result.issues:
            lines.append("Issues found:")
            for issue in result.issues:
                severity_icon = "🔴" if issue["severity"] == "error" else "🟡" if issue["severity"] == "warning" else "🔵"
                lines.append(f"  {severity_icon} {issue['message']}")
                lines.append(f"     💡 {issue['suggestion']}")
            lines.append("")

        if result.suggestions:
            lines.append("Suggestions:")
            for suggestion in result.suggestions:
                lines.append(f"  • {suggestion}")
            lines.append("")

        return "\n".join(lines)
