"""Raw data ingestion workflow for Phase 2."""

from __future__ import annotations

import logging
import shutil
from dataclasses import asdict, dataclass
from pathlib import Path

from src.config import IngestionPaths
from src.utils.io import compute_sha256

LOGGER = logging.getLogger(__name__)


@dataclass(frozen=True)
class FileCopySummary:
    """Summary information for a copied source artifact."""

    source_path: str
    destination_path: str
    size_bytes: int
    sha256: str


def copy_raw_file(source: Path, destination: Path) -> FileCopySummary:
    """Copy a source file to the raw data directory without modification.

    Args:
        source: Original file path.
        destination: Raw-data destination path.

    Returns:
        Metadata describing the copied artifact.
    """
    destination.parent.mkdir(parents=True, exist_ok=True)
    source_checksum = compute_sha256(source)
    if destination.exists():
        destination_checksum = compute_sha256(destination)
        if destination_checksum != source_checksum:
            raise FileExistsError(
                f"Refusing to overwrite immutable raw file: {destination}"
            )
        checksum = destination_checksum
        size_bytes = destination.stat().st_size
        LOGGER.info("Raw file already present and unchanged: %s", destination)
    else:
        shutil.copy2(source, destination)
        checksum = compute_sha256(destination)
        size_bytes = destination.stat().st_size
        LOGGER.info("Copied %s to %s", source, destination)
    summary = FileCopySummary(
        source_path=str(source),
        destination_path=str(destination),
        size_bytes=size_bytes,
        sha256=checksum,
    )
    return summary


def ingest_raw_data(paths: IngestionPaths | None = None) -> dict[str, dict[str, str | int]]:
    """Copy the authoritative source files into the raw data area.

    Args:
        paths: Project ingestion paths. Defaults to standard project locations.

    Returns:
        A dictionary keyed by artifact name with copy metadata.
    """
    active_paths = paths or IngestionPaths()
    csv_summary = copy_raw_file(active_paths.source_csv, active_paths.raw_csv)
    metadata_summary = copy_raw_file(
        active_paths.source_metadata,
        active_paths.raw_metadata,
    )
    return {
        "csv": asdict(csv_summary),
        "metadata": asdict(metadata_summary),
    }


if __name__ == "__main__":
    from src.logging_config import configure_logging

    configure_logging()
    ingest_raw_data()
