# Copyright 2026 4f4d
# Licensed under the Apache License, Version 2.0

"""Tests for f1radio.export."""

import csv
import json
import pytest

from f1radio.export import export_json, export_csv


class TestExportJson:
    def test_basic(self, sample_session, tmp_path):
        path = str(tmp_path / "test.json")
        export_json(sample_session, path)

        with open(path) as f:
            data = json.load(f)

        assert data["year"] == 2023
        assert data["race"] == "Italian Grand Prix"
        assert data["total_clips"] == 3
        assert len(data["clips"]) == 3
        assert data["clips"][0]["driver"] == "VER"

    def test_empty_session(self, tmp_path):
        from f1radio.models import Session, ClipList
        session = Session(
            year=2023, race="Test", session_type="Race",
            session_key=1, meeting_key=1, clips=ClipList(),
        )
        path = str(tmp_path / "empty.json")
        export_json(session, path)

        with open(path) as f:
            data = json.load(f)
        assert data["total_clips"] == 0
        assert data["clips"] == []


class TestExportCsv:
    def test_basic(self, sample_session, tmp_path):
        path = str(tmp_path / "test.csv")
        export_csv(sample_session, path)

        with open(path, newline="") as f:
            reader = csv.DictReader(f)
            rows = list(reader)

        assert len(rows) == 3
        assert rows[0]["driver"] == "VER"
        assert "context_position" in rows[0]

    def test_empty_session(self, tmp_path):
        from f1radio.models import Session, ClipList
        session = Session(
            year=2023, race="Test", session_type="Race",
            session_key=1, meeting_key=1, clips=ClipList(),
        )
        path = str(tmp_path / "empty.csv")
        export_csv(session, path)
        # Should not crash, file should exist
        assert (tmp_path / "empty.csv").exists()
