from __future__ import annotations

import gzip
import hashlib
import os
from pathlib import Path
from typing import Any

from .utils import canonical_json, sha256_file


class JsonlGzipPartWriter:
    def __init__(
        self,
        directory: Path,
        max_records_per_part: int,
        compression_level: int = 1,
    ) -> None:
        if max_records_per_part < 1:
            raise ValueError("max_records_per_part must be positive")
        if not 0 <= compression_level <= 9:
            raise ValueError("compression_level must be between 0 and 9")
        self.directory = directory
        self.directory.mkdir(parents=True, exist_ok=True)
        self.max_records_per_part = max_records_per_part
        self.compression_level = compression_level
        self._handle = None
        self._tmp_path: Path | None = None
        self._final_path: Path | None = None
        self._part_records = 0
        self._part_index = 0
        self._total_records = 0
        self._sequence_hash = hashlib.sha256()
        self.parts: list[dict[str, Any]] = []

    def _open_part(self) -> None:
        self._part_index += 1
        name = f"part-{self._part_index:06d}.jsonl.gz"
        self._final_path = self.directory / name
        self._tmp_path = self.directory / f".{name}.tmp"
        self._handle = gzip.open(
            self._tmp_path,
            mode="wt",
            encoding="utf-8",
            newline="\n",
            compresslevel=self.compression_level,
        )
        self._part_records = 0

    def write(self, record: dict[str, Any]) -> None:
        if self._handle is None:
            self._open_part()
        if self._part_records >= self.max_records_per_part:
            self._close_part()
            self._open_part()

        line = canonical_json(record)
        self._handle.write(line)
        self._handle.write("\n")
        self._part_records += 1
        self._total_records += 1
        self._sequence_hash.update(str(record["fingerprint"]).encode("ascii"))
        self._sequence_hash.update(b"\n")

    def _close_part(self) -> None:
        if self._handle is None or self._tmp_path is None or self._final_path is None:
            return
        self._handle.flush()
        self._handle.close()
        self._handle = None
        os.replace(self._tmp_path, self._final_path)
        self.parts.append({
            "part_index": self._part_index,
            "file_name": self._final_path.name,
            "record_count": self._part_records,
            "size_bytes": self._final_path.stat().st_size,
            "sha256": sha256_file(self._final_path),
            "path": str(self._final_path),
        })
        self._tmp_path = None
        self._final_path = None
        self._part_records = 0

    def abort(self) -> None:
        if self._handle is not None:
            try:
                self._handle.close()
            finally:
                self._handle = None
        if self._tmp_path is not None and self._tmp_path.exists():
            self._tmp_path.unlink()
        self._tmp_path = None
        self._final_path = None

    def finish(self) -> dict[str, Any]:
        self._close_part()
        return {
            "record_count": self._total_records,
            "records_sequence_sha256": self._sequence_hash.hexdigest(),
            "parts": self.parts,
        }
