"""
CSV Schedule Generation System.
Generates comprehensive CSV files with detailed formatting for all cruise activities.
"""

import csv
import logging
from pathlib import Path
from typing import List

from cruiseplan.calculators.scheduler import ActivityRecord
from cruiseplan.core.validation import CruiseConfig
from cruiseplan.utils.activity_utils import (
    format_operation_action,
    round_time_to_minute,
)
from cruiseplan.utils.coordinates import UnitConverter

logger = logging.getLogger(__name__)


class CSVGenerator:
    """
    Manages CSV generation for cruise schedules with comprehensive formatting.
    """

    def __init__(self):
        """Initialize the CSV generator."""
        pass

    def generate_schedule_csv(
        self, config: CruiseConfig, timeline: List[ActivityRecord], output_file: Path
    ) -> Path:
        """
        Generate CSV schedule output with comprehensive formatting.

        Parameters
        ----------
        config : CruiseConfig
            The cruise configuration object
        timeline : List[ActivityRecord]
            Timeline generated by the scheduler
        output_file : Path
            Path to output CSV file

        Returns
        -------
        Path
            Path to generated CSV file
        """
        # Define CSV fieldnames with comprehensive column structure
        fieldnames = [
            "activity",
            "label",
            "operation_action",
            "start_time",
            "end_time",
            "Transit dist [nm]",
            "Vessel speed [kt]",
            "Duration [hrs]",
            "Depth [m]",
            "Lat [deg]",
            "Lon [deg]",
            "Lat [deg_rounded]",
            "Lat [min]",
            "Lon [deg_rounded]",
            "Lon [min]",
            "leg_name",
        ]

        # Write CSV file
        output_file.parent.mkdir(parents=True, exist_ok=True)
        with open(output_file, "w", newline="", encoding="utf-8") as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

            writer.writeheader()
            for activity in timeline:
                # Format datetime for CSV - round to nearest minute
                start_time = round_time_to_minute(activity["start_time"])
                end_time = round_time_to_minute(activity["end_time"])

                # Convert duration to hours and round to nearest 0.1 hour
                duration_hours = round(activity["duration_minutes"] / 60.0, 1)

                # Round transit distance to nearest 0.1 nm
                transit_dist_nm = round(activity.get("transit_dist_nm", 0.0), 1)

                # Vessel speed - 0 for station operations, actual speed for transits
                if activity.get("activity", "").lower() == "transit":
                    vessel_speed = activity.get("vessel_speed_kt", 0)
                else:
                    vessel_speed = 0  # Station operations have 0 vessel speed

                # Format operation and action
                operation_action = format_operation_action(
                    activity.get("operation_type", ""), activity.get("action", "")
                )

                # Coordinate conversions using existing utilities
                lat_decimal = activity["lat"]
                lon_decimal = activity["lon"]
                lat_deg_float, lat_min = UnitConverter.decimal_degrees_to_dmm(
                    lat_decimal
                )
                lon_deg_float, lon_min = UnitConverter.decimal_degrees_to_dmm(
                    lon_decimal
                )
                # Preserve sign for rounded degrees
                lat_deg_rounded = (
                    int(lat_deg_float) if lat_decimal >= 0 else -int(lat_deg_float)
                )
                lon_deg_rounded = (
                    int(lon_deg_float) if lon_decimal >= 0 else -int(lon_deg_float)
                )
                lat_min = round(lat_min, 2)
                lon_min = round(lon_min, 2)

                row = {
                    "activity": activity["activity"],
                    "label": activity["label"],
                    "operation_action": operation_action,
                    "start_time": start_time.isoformat(),
                    "end_time": end_time.isoformat(),
                    "Transit dist [nm]": transit_dist_nm,
                    "Vessel speed [kt]": vessel_speed,
                    "Duration [hrs]": duration_hours,
                    "Depth [m]": round(activity.get("depth", 0)),  # Whole number
                    "Lat [deg]": round(
                        lat_decimal, 6
                    ),  # High precision decimal degrees
                    "Lon [deg]": round(
                        lon_decimal, 6
                    ),  # High precision decimal degrees
                    "Lat [deg_rounded]": lat_deg_rounded,
                    "Lat [min]": lat_min,
                    "Lon [deg_rounded]": lon_deg_rounded,
                    "Lon [min]": lon_min,
                    "leg_name": activity.get("leg_name", ""),
                }

                writer.writerow(row)

        logger.info(f"CSV schedule saved to: {output_file}")
        return output_file


def generate_csv_schedule(
    config: CruiseConfig, timeline: List[ActivityRecord], output_file: Path
) -> Path:
    """
    Main interface to generate CSV schedule from scheduler timeline.

    Parameters
    ----------
    config : CruiseConfig
        The cruise configuration object
    timeline : List[ActivityRecord]
        Timeline generated by the scheduler
    output_file : Path
        Path to output CSV file

    Returns
    -------
    Path
        Path to generated CSV file
    """
    generator = CSVGenerator()
    return generator.generate_schedule_csv(config, timeline, output_file)
