"""Artefactos temporales del flujo de carga individual."""

from __future__ import annotations

import re
from pathlib import Path


class LocalIndividualUploadFileStore:
    def __init__(self, base_dir: Path) -> None:
        self.base_dir = Path(base_dir) / "_individual_uploads"
        self.base_dir.mkdir(parents=True, exist_ok=True)

    def save_file(self, upload_id: str, filename: str, data: bytes) -> str:
        safe_name = self._safe_filename(filename)
        upload_dir = self.base_dir / upload_id
        upload_dir.mkdir(parents=True, exist_ok=True)
        target = upload_dir / safe_name
        target.write_bytes(data)
        return str(target)

    def delete_file(self, file_path: str) -> None:
        if not str(file_path or "").strip():
            return
        path = Path(file_path)
        if path.exists():
            path.unlink()
        parent = path.parent
        root = self.base_dir.resolve(strict=False)
        while parent.resolve(strict=False) != root:
            if any(parent.iterdir()):
                break
            parent.rmdir()
            parent = parent.parent

    def _safe_filename(self, filename: str) -> str:
        raw = Path(str(filename or "").strip()).name or "documento.pdf"
        stem = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(raw).stem).strip("._-") or "documento"
        suffix = Path(raw).suffix.lower() or ".pdf"
        if suffix != ".pdf":
            suffix = ".pdf"
        return f"{stem}{suffix}"
