"""
Persist uploaded driver verification documents under local_upload_dir.
"""
import uuid
from pathlib import Path
from typing import Optional

from fastapi import UploadFile

from app.config import settings
from app.models.driver import DocumentType

MAX_DRIVER_DOCUMENT_BYTES = 10 * 1024 * 1024

_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent


def _uploads_dir() -> Path:
    rel = settings.local_upload_dir.lstrip("./")
    return _PROJECT_ROOT / rel


async def save_driver_document(
    driver_id: int,
    document_type: DocumentType,
    upload: UploadFile,
) -> str:
    """
    Validate and persist an uploaded driver document, returning its public URL path.
    """
    filename = (upload.filename or "").strip()
    if not filename:
        raise ValueError("Document file is required")

    raw = await upload.read()
    if not raw:
        raise ValueError("Uploaded document is empty")
    if len(raw) > MAX_DRIVER_DOCUMENT_BYTES:
        raise ValueError("Document too large (max 10MB)")

    ext = _detect_extension(raw, upload.content_type, filename)

    root = _uploads_dir()
    dest_dir = root / "driver-documents" / str(driver_id) / document_type.value
    dest_dir.mkdir(parents=True, exist_ok=True)

    stored_name = f"{uuid.uuid4().hex}{ext}"
    path = dest_dir / stored_name
    path.write_bytes(raw)

    return f"/uploads/driver-documents/{driver_id}/{document_type.value}/{stored_name}"


def _detect_extension(raw: bytes, content_type: Optional[str], filename: str) -> str:
    mime = (content_type or "").strip().lower()
    if raw.startswith(b"\xff\xd8\xff"):
        return ".jpg"
    if raw.startswith(b"\x89PNG\r\n\x1a\n"):
        return ".png"
    if raw.startswith(b"RIFF") and len(raw) >= 12 and raw[8:12] == b"WEBP":
        return ".webp"
    if raw.startswith(b"%PDF"):
        return ".pdf"

    if mime in {"image/jpeg", "image/jpg"}:
        return ".jpg"
    if mime == "image/png":
        return ".png"
    if mime == "image/webp":
        return ".webp"
    if mime == "application/pdf":
        return ".pdf"

    suffix = Path(filename).suffix.lower()
    if suffix in {".jpg", ".jpeg"}:
        return ".jpg"
    if suffix in {".png", ".webp", ".pdf"}:
        return suffix

    raise ValueError("Unsupported document type (use JPEG, PNG, WebP, or PDF)")
