from __future__ import annotations

from dataclasses import dataclass
import gzip
import hashlib
import os
from pathlib import Path
import re
import uuid

from .database import APP_ROOT


JOB_UID_PATTERN = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")


@dataclass(frozen=True)
class StoredArtifact:
    relative_path: str
    compressed_size_bytes: int
    uncompressed_size_bytes: int
    sha256: str


def calculation_store_root() -> Path:
    configured = os.getenv("FSE3D_CALCULATION_STORE_DIR", "").strip()
    path = Path(configured).expanduser() if configured else APP_ROOT / "tmp" / "calculations"
    return (path if path.is_absolute() else APP_ROOT / path).resolve()


class CalculationArtifactStore:
    def __init__(self, root: Path | None = None) -> None:
        self.root = (root or calculation_store_root()).resolve()

    def initialize(self) -> None:
        self.root.mkdir(parents=True, exist_ok=True)
        try:
            self.root.chmod(0o700)
        except OSError:
            pass

    def write_request(self, job_uid: str, request_bytes: bytes) -> StoredArtifact:
        job_dir = self.prepare_job(job_uid)
        path = job_dir / "request.json.gz"
        self._write_gzip_atomic(path, request_bytes)
        return StoredArtifact(
            relative_path=self.relative_path(path),
            compressed_size_bytes=path.stat().st_size,
            uncompressed_size_bytes=len(request_bytes),
            sha256=hashlib.sha256(request_bytes).hexdigest(),
        )

    def prepare_attempt(self, job_uid: str, run_token: str) -> tuple[Path, Path]:
        self._validate_uuid(run_token, "token de execucao")
        job_dir = self.prepare_job(job_uid)
        return (
            job_dir / f"result-{run_token}.json.gz",
            job_dir / f"manifest-{run_token}.json",
        )

    def prepare_job(self, job_uid: str) -> Path:
        self._validate_uuid(job_uid, "ID do trabalho")
        self.initialize()
        path = self.root / job_uid
        path.mkdir(mode=0o700, parents=False, exist_ok=True)
        return path

    def resolve_artifact(self, relative_path: str) -> Path:
        if not relative_path or Path(relative_path).is_absolute():
            raise ValueError("Caminho de artefato invalido.")
        candidate = (self.root / relative_path).resolve()
        if candidate == self.root or self.root not in candidate.parents:
            raise ValueError("Caminho de artefato fora do armazenamento permitido.")
        return candidate

    def relative_path(self, path: Path) -> str:
        resolved = path.resolve()
        if self.root not in resolved.parents:
            raise ValueError("Artefato fora do armazenamento permitido.")
        return resolved.relative_to(self.root).as_posix()

    def read_gzip_bytes(self, relative_path: str, *, max_bytes: int) -> bytes:
        path = self.resolve_artifact(relative_path)
        with gzip.open(path, "rb") as handle:
            data = handle.read(max_bytes + 1)
        if len(data) > max_bytes:
            raise ValueError("Artefato descompactado excede o limite permitido.")
        return data

    def remove_artifact(self, relative_path: str | None) -> None:
        if not relative_path:
            return
        try:
            self.resolve_artifact(relative_path).unlink(missing_ok=True)
        except (OSError, ValueError):
            return

    @staticmethod
    def _validate_uuid(value: str, label: str) -> None:
        normalized = str(value).lower()
        if not JOB_UID_PATTERN.fullmatch(normalized):
            raise ValueError(f"{label} invalido.")
        try:
            uuid.UUID(normalized)
        except ValueError as exc:
            raise ValueError(f"{label} invalido.") from exc

    @staticmethod
    def _write_gzip_atomic(path: Path, data: bytes) -> None:
        temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
        try:
            with temporary.open("xb") as raw:
                with gzip.GzipFile(
                    filename="",
                    mode="wb",
                    fileobj=raw,
                    compresslevel=6,
                    mtime=0,
                ) as compressed:
                    compressed.write(data)
                raw.flush()
                os.fsync(raw.fileno())
            try:
                temporary.chmod(0o600)
            except OSError:
                pass
            os.replace(temporary, path)
        finally:
            temporary.unlink(missing_ok=True)


artifact_store = CalculationArtifactStore()
