"""File upload utility — local (dev) atau Google Drive (production).

Semua caller cukup buat UploadContext, tidak perlu tau path logic.
"""

import uuid
from dataclasses import dataclass
from datetime import date
from pathlib import Path

from app.core.config import settings

UPLOAD_DIR = Path("uploads")

_ALLOWED_MAGIC = {
    b'\xff\xd8\xff': 'jpg',        # JPEG
    b'\x89PNG': 'png',             # PNG
    b'%PDF': 'pdf',                # PDF
}


def _validate_file_type(data: bytes, filename: str) -> None:
    """Reject files whose content doesn't match a known safe type."""
    ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
    if ext not in {'jpg', 'jpeg', 'png', 'pdf'}:
        raise ValueError(f"Tipe file tidak didukung: {ext}")
    for magic, typ in _ALLOWED_MAGIC.items():
        if data[:len(magic)] == magic:
            return
    # PDF check — '%PDF' at start
    if data[:4] == b'%PDF':
        return
    raise ValueError("Konten file tidak sesuai ekstensi yang diizinkan")


@dataclass
class UploadContext:
    spbu_code: str  # nomor_pertamina SPBU, e.g. "112201"
    tipe: str       # "absensi" | "housekeeping" | "stock" | "penerimaan" | "penyetoran" | "penebusan" | "expenses" | "laporan"
    tanggal: date


def _unique_filename(filename: str, tahun: int, bulan: int) -> str:
    safe = filename.replace("/", "_").replace("\\", "_")
    return f"{tahun}{bulan:02d}-{uuid.uuid4().hex[:8]}-{safe}"


async def get_spbu_code(db, spbu_id: int) -> str:
    """Fetch nomor_pertamina for a SPBU. Falls back to str(spbu_id) if not found."""
    from sqlalchemy import select
    from app.models.spbu import Spbu
    result = await db.execute(select(Spbu.nomor_pertamina).where(Spbu.id == spbu_id))
    code = result.scalar_one_or_none()
    return code or str(spbu_id)


async def delete_file(stored_url: str | None) -> None:
    """
    Delete a previously uploaded file. Fire-and-forget — errors are logged, never raised.

    Handles both local paths (/uploads/...) and Google Drive URLs.
    """
    if not stored_url:
        return
    import logging
    logger = logging.getLogger(__name__)
    try:
        if stored_url.startswith("https://drive.google.com/"):
            from app.utils.gdrive import gdrive_delete
            gdrive_delete(stored_url)
        elif stored_url.startswith("/uploads/"):
            # e.g. /uploads/dev/1/laporan/202604-abc-foto.jpg → uploads/dev/1/laporan/...
            rel = stored_url[len("/uploads/"):]  # strip leading /uploads/
            (UPLOAD_DIR / rel).unlink(missing_ok=True)
    except Exception as e:
        logger.warning("delete_file: gagal hapus '%s' — %s", stored_url, e)


async def save_upload(file_bytes: bytes, filename: str, ctx: UploadContext) -> str:
    """
    Simpan file ke storage yang sesuai environment.

    Path: {env}/{spbu_code}/{tipe}/{tahun}{bulan}-{uuid}-{filename}
    """
    _validate_file_type(file_bytes, filename)
    tahun = ctx.tanggal.year
    bulan = ctx.tanggal.month
    unique_name = _unique_filename(filename, tahun, bulan)
    env = "live" if settings.is_production else "dev"

    if settings.STORAGE_TYPE == "gdrive":
        from app.utils.gdrive import gdrive_upload
        return gdrive_upload(file_bytes, unique_name, ctx.spbu_code, ctx.tipe, env)

    dest_dir = UPLOAD_DIR / env / ctx.spbu_code / ctx.tipe
    dest_dir.mkdir(parents=True, exist_ok=True)
    (dest_dir / unique_name).write_bytes(file_bytes)
    return f"/uploads/{env}/{ctx.spbu_code}/{ctx.tipe}/{unique_name}"
