"""Tests for validation report generation."""

from __future__ import annotations

import json
import tempfile
from pathlib import Path

from orxaq.fabric.validation.metrics import ValidationMetrics
from orxaq.fabric.validation.report import generate_report, save_report


def _sample_metrics() -> ValidationMetrics:
    return ValidationMetrics(
        shd=3,
        precision=0.8,
        recall=0.7,
        f1=0.74,
        orientation_accuracy=0.9,
        fdr=0.2,
        true_positives=7,
        false_positives=2,
        false_negatives=3,
        reversed_edges=1,
        total_true_edges=10,
        total_predicted_edges=9,
    )


class TestGenerateReport:
    def test_creates_report(self):
        m = _sample_metrics()
        r = generate_report("pc", 5, 1000, m, [("A", "B")], [("A", "B"), ("B", "C")])
        assert r.algorithm == "pc"
        assert r.variables_count == 5
        assert r.data_rows == 1000
        assert r.timestamp > 0

    def test_to_json(self):
        m = _sample_metrics()
        r = generate_report("pc", 5, 1000, m, [("A", "B")], [("A", "B")])
        j = r.to_json()
        data = json.loads(j)
        assert data["algorithm"] == "pc"
        assert data["metrics"]["shd"] == 3

    def test_to_markdown(self):
        m = _sample_metrics()
        r = generate_report("pc", 5, 1000, m, [], [])
        md = r.to_markdown()
        assert "# Validation Report" in md
        assert "SHD" in md
        assert "0.800" in md

    def test_to_dict(self):
        m = _sample_metrics()
        r = generate_report("consensus", 10, 5000, m, [], [])
        d = r.to_dict()
        assert d["algorithm"] == "consensus"
        assert d["variables_count"] == 10


class TestSaveReport:
    def test_save_json(self):
        m = _sample_metrics()
        r = generate_report("pc", 5, 1000, m, [], [])
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "report.json"
            save_report(r, path)
            assert path.exists()
            data = json.loads(path.read_text())
            assert data["algorithm"] == "pc"

    def test_save_markdown(self):
        m = _sample_metrics()
        r = generate_report("pc", 5, 1000, m, [], [])
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "report.md"
            save_report(r, path)
            assert path.exists()
            content = path.read_text()
            assert "# Validation Report" in content
