"""Output formatters for CLI results."""

import json
from datetime import datetime

from ai_qa.core.result import ValidationResult


def format_json(result: ValidationResult) -> str:
    """Format ValidationResult as JSON."""
    passed_count = sum(1 for c in result.checks if c.passed)
    total_checks = len(result.checks)

    # Aggregate tokens from all checks
    total_tokens = {"input": 0, "output": 0}
    for check in result.checks:
        total_tokens["input"] += check.tokens_used.get("input", 0)
        total_tokens["output"] += check.tokens_used.get("output", 0)

    return json.dumps(
        {
            "passed_rate": passed_count / total_checks if total_checks > 0 else 0,
            "total_checks": total_checks,
            "passed": passed_count,
            "failed": total_checks - passed_count,
            "total_cost_usd": result.total_cost,
            "total_tokens": total_tokens,
            "checks": [
                {
                    "name": check.name,
                    "score": check.score,
                    "passed": check.passed,
                    "threshold": check.threshold,
                    "evidence": check.evidence,
                    "cost_usd": check.cost_usd,
                    "tokens_used": check.tokens_used,
                    "cached": check.cached,
                    "version": check.check_version,
                }
                for check in result.checks
            ],
        },
        indent=2,
    )


def format_table(result: ValidationResult) -> str:
    """Format ValidationResult as ASCII table."""
    output = "\n" + "=" * 100 + "\n"
    output += "AI-QA Validation Results\n"
    output += "=" * 100 + "\n\n"

    # Summary section
    passed_count = sum(1 for c in result.checks if c.passed)
    failed_count = sum(1 for c in result.checks if not c.passed)
    total_checks = len(result.checks)
    passed_rate = passed_count / total_checks if total_checks > 0 else 0

    # Aggregate tokens from all checks
    total_tokens = {"input": 0, "output": 0}
    for check in result.checks:
        total_tokens["input"] += check.tokens_used.get("input", 0)
        total_tokens["output"] += check.tokens_used.get("output", 0)
    total_token_count = total_tokens.get("input", 0) + total_tokens.get("output", 0)

    output += "SUMMARY\n"
    output += "-" * 100 + "\n"
    output += f"Pass Rate:        {passed_rate*100:>6.1f}%\n"
    output += f"Passed Checks:    {passed_count:>6d} ✓\n"
    output += f"Failed Checks:    {failed_count:>6d} ✗\n"
    output += f"Total Cost:       ${result.total_cost:>8.4f}\n"
    output += f"Total Tokens:     {total_token_count:>6d}\n"
    output += "\n"

    # Detailed checks section
    output += "CHECK RESULTS\n"
    output += "-" * 100 + "\n"
    output += f"{'Check':<25} {'Score':>8} {'Status':>8} {'Evidence':<50} {'Cost':>8}\n"
    output += "-" * 100 + "\n"

    for check in result.checks:
        status = "✓ PASS" if check.passed else "✗ FAIL"
        evidence = (
            check.evidence[:47] + "..."
            if len(check.evidence) > 50
            else check.evidence
        )
        cost = f"${check.cost_usd:.4f}"

        output += f"{check.name:<25} {check.score:>8.2f} {status:>8} {evidence:<50} {cost:>8}\n"

    output += "-" * 100 + "\n"

    # Detailed evidence section
    output += "\nDETAILED EVIDENCE\n"
    output += "-" * 100 + "\n"

    for check in result.checks:
        status = "✓ PASS" if check.passed else "✗ FAIL"
        output += f"\n[{status}] {check.name}\n"
        output += f"    Score:     {check.score:.2f}/{check.threshold:.2f} (threshold)\n"
        output += f"    Evidence:  {check.evidence}\n"
        output += f"    Cost:      ${check.cost_usd:.4f}\n"
        if check.tokens_used:
            output += f"    Tokens:    {check.tokens_used}\n"
        if check.cached:
            output += f"    Cached:    Yes (from previous run)\n"

    output += "\n" + "=" * 100 + "\n"

    return output


def format_html(result: ValidationResult) -> str:
    """Format ValidationResult as HTML."""
    passed_count = sum(1 for c in result.checks if c.passed)
    failed_count = sum(1 for c in result.checks if not c.passed)
    total_checks = len(result.checks)
    passed_rate = passed_count / total_checks if total_checks > 0 else 0

    html = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AI-QA Validation Report</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }}
        .container {{ max-width: 1200px; margin: 0 auto; }}
        .header {{
            background: white;
            border-radius: 12px;
            padding: 40px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }}
        .header h1 {{ color: #2c3e50; margin-bottom: 10px; }}
        .header p {{ color: #7f8c8d; }}
        .summary {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }}
        .stat {{
            background: white;
            padding: 25px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: transform 0.2s;
        }}
        .stat:hover {{ transform: translateY(-5px); }}
        .stat-value {{
            font-size: 36px;
            font-weight: bold;
            margin: 10px 0;
        }}
        .stat-label {{ color: #7f8c8d; font-size: 14px; }}
        .passed {{ color: #27ae60; }}
        .failed {{ color: #e74c3c; }}
        .checks-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }}
        .check-card {{
            background: white;
            padding: 20px;
            border-radius: 12px;
            border-left: 5px solid #ddd;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }}
        .check-card.pass {{ border-left-color: #27ae60; }}
        .check-card.fail {{ border-left-color: #e74c3c; }}
        .check-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }}
        .check-name {{ font-weight: 600; color: #2c3e50; }}
        .check-status {{
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }}
        .check-status.pass {{ background: #d4edda; color: #155724; }}
        .check-status.fail {{ background: #f8d7da; color: #721c24; }}
        .check-detail {{ margin: 8px 0; font-size: 14px; }}
        .check-detail label {{ color: #7f8c8d; font-weight: 500; }}
        .check-evidence {{
            margin-top: 10px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 6px;
            font-size: 13px;
            color: #555;
            border-left: 3px solid #667eea;
        }}
        .score-bar {{
            background: #ecf0f1;
            height: 20px;
            border-radius: 10px;
            overflow: hidden;
            margin: 5px 0;
        }}
        .score-fill {{
            height: 100%;
            background: linear-gradient(90deg, #27ae60, #2ecc71);
            transition: width 0.3s;
        }}
        .score-fill.low {{ background: linear-gradient(90deg, #e74c3c, #c0392b); }}
        footer {{
            text-align: center;
            color: white;
            margin-top: 40px;
            padding: 20px;
            font-size: 13px;
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🧪 AI-QA Validation Report</h1>
            <p>Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        </div>

        <div class="summary">
            <div class="stat">
                <div class="stat-label">Pass Rate</div>
                <div class="stat-value">{passed_rate*100:.1f}%</div>
            </div>
            <div class="stat">
                <div class="stat-label">Passed</div>
                <div class="stat-value passed">{passed_count}</div>
            </div>
            <div class="stat">
                <div class="stat-label">Failed</div>
                <div class="stat-value failed">{failed_count}</div>
            </div>
            <div class="stat">
                <div class="stat-label">Total Cost</div>
                <div class="stat-value">${result.total_cost:.4f}</div>
            </div>
        </div>

        <div class="checks-grid">
"""

    for check in result.checks:
        status_class = "pass" if check.passed else "fail"
        status_text = "✓ PASS" if check.passed else "✗ FAIL"
        score_pct = min(int(check.score * 100), 100)
        score_fill_class = "low" if check.score < check.threshold else ""

        html += f"""            <div class="check-card {status_class}">
                <div class="check-header">
                    <div class="check-name">{check.name}</div>
                    <div class="check-status {status_class}">{status_text}</div>
                </div>
                <div class="check-detail">
                    <label>Score:</label> {check.score:.2f} / {check.threshold:.2f}
                </div>
                <div class="score-bar">
                    <div class="score-fill {score_fill_class}" style="width: {score_pct}%"></div>
                </div>
                <div class="check-detail">
                    <label>Cost:</label> ${check.cost_usd:.4f}
                </div>
                <div class="check-evidence">{check.evidence}</div>
            </div>
"""

    html += """        </div>

        <footer>
            <p>Powered by AI-QA SDK • Universal AI Validation</p>
        </footer>
    </div>
</body>
</html>
"""

    return html
