"""End-to-end tests: parse → classify → analyze → report for all 4 platforms."""

import pytest
from pathlib import Path

from ai_checkup.parsers import detect_and_parse
from ai_checkup.analyzer import analyze
from ai_checkup.report import generate_all


def _run_e2e(input_path, output_dir, expected_platform):
    """Full pipeline for one platform."""
    # Parse
    convs = detect_and_parse(input_path)
    assert len(convs) == 20
    assert convs[0].platform == expected_platform

    # Analyze
    result = analyze(convs)
    assert result.total_conversations == 20
    assert len(result.dimensions) == 6
    assert len(result.weeks) > 0

    # Report
    generate_all(result, output_dir)
    assert (output_dir / "radar.png").exists()
    assert (output_dir / "report.md").exists()
    assert (output_dir / "data.json").exists()

    # Validate radar.png is a valid PNG
    with open(output_dir / "radar.png", "rb") as f:
        header = f.read(8)
        assert header[:4] == b"\x89PNG"

    # Validate report.md has content
    report = (output_dir / "report.md").read_text(encoding="utf-8")
    assert "六维能力分析报告" in report
    assert "提问力" in report
    assert "判断力" in report

    # Validate data.json has all dimensions
    import json
    with open(output_dir / "data.json", encoding="utf-8") as f:
        data = json.load(f)
    assert len(data["dimensions"]) == 6
    for dim_key in ["questioning", "judgment", "hands_on", "deep_thinking", "execution", "narrative"]:
        assert dim_key in data["dimensions"]
        assert 0 <= data["dimensions"][dim_key]["score"] <= 100

    # Scores should be consistent between result and JSON
    for dim_key in data["dimensions"]:
        assert data["dimensions"][dim_key]["score"] == result.dimensions[dim_key].score

    return result


class TestE2EChatGPT:
    def test_full_pipeline(self, chatgpt_path, tmp_path):
        output_dir = tmp_path / "chatgpt_output"
        result = _run_e2e(chatgpt_path, output_dir, "chatgpt")
        # Verify six dimensions all have reasonable scores
        for dim in result.dimensions.values():
            assert dim.score >= 0


class TestE2EClaude:
    def test_full_pipeline(self, claude_path, tmp_path):
        output_dir = tmp_path / "claude_output"
        result = _run_e2e(claude_path, output_dir, "claude")


class TestE2EGemini:
    def test_full_pipeline(self, gemini_path, tmp_path):
        output_dir = tmp_path / "gemini_output"
        result = _run_e2e(gemini_path, output_dir, "gemini")


class TestE2ECSV:
    def test_full_pipeline(self, csv_path, tmp_path):
        output_dir = tmp_path / "csv_output"
        result = _run_e2e(csv_path, output_dir, "csv")


class TestE2EConsistency:
    """All 4 platforms parse the same 20 conversations → scores should be similar."""

    def test_cross_platform_scores(self, chatgpt_path, claude_path, gemini_path, csv_path, tmp_path):
        results = {}
        for name, path, platform in [
            ("chatgpt", chatgpt_path, "chatgpt"),
            ("claude", claude_path, "claude"),
            ("gemini", gemini_path, "gemini"),
            ("csv", csv_path, "csv"),
        ]:
            convs = detect_and_parse(path)
            results[name] = analyze(convs)

        # All should have same number of conversations
        for name, result in results.items():
            assert result.total_conversations == 20, f"{name} has {result.total_conversations}"

        # Scores should be identical across platforms (same underlying data)
        ref_scores = {
            k: results["chatgpt"].dimensions[k].score
            for k in results["chatgpt"].dimensions
        }
        for platform in ["gemini", "csv"]:
            for dim_key, ref_score in ref_scores.items():
                actual = results[platform].dimensions[dim_key].score
                assert actual == ref_score, (
                    f"{platform}.{dim_key}: {actual} != chatgpt.{dim_key}: {ref_score}"
                )
