# Copyright 2026 4f4d
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Export session data to JSON and CSV formats."""

from __future__ import annotations

import csv
import json
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from f1radio.models import Session


def export_json(session: "Session", path: str) -> None:
    """Export session data to a JSON file.

    Output includes session metadata and all clips with full context.

    Args:
        session: Session object to export.
        path: Output file path.
    """
    data = {
        "year": session.year,
        "race": session.race,
        "session_type": session.session_type,
        "session_key": session.session_key,
        "total_clips": len(session.clips),
        "drivers": session.drivers,
        "driver_counts": session.driver_counts,
        "clips": [clip.to_dict() for clip in session.clips],
    }

    Path(path).parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, default=str, ensure_ascii=False)


def export_csv(session: "Session", path: str) -> None:
    """Export session data to a CSV file.

    Creates a flat table with one row per clip, including all context fields.

    Args:
        session: Session object to export.
        path: Output file path.
    """
    if not session.clips:
        Path(path).parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w", encoding="utf-8", newline="") as f:
            writer = csv.writer(f)
            writer.writerow(["No clips available"])
        return

    # Get all columns from first clip's dict
    sample = session.clips[0].to_dict()
    fieldnames = list(sample.keys())

    Path(path).parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction="ignore")
        writer.writeheader()
        for clip in session.clips:
            row = clip.to_dict()
            # Flatten lists to semicolon-separated strings for CSV
            for key, value in row.items():
                if isinstance(value, list):
                    row[key] = "; ".join(str(v) for v in value)
            writer.writerow(row)
