"""Engine adapters over Django storage: assets by id, images by URL (SSRF-safe, disk cache)."""

from __future__ import annotations

import hashlib
import time
from pathlib import Path

from django.conf import settings

from snapfile.assets.models import Asset
from snapfile.core import ids
from snapfile.core.http import FetchError, request
from snapfile.core.storage import store
from snapfile.projects.models import Project
from snapfile_render.providers import ImageRef, decode_data_uri, image_size
from snapfile_render.svg import looks_like_svg

IMAGE_URL_CACHE_TTL = 24 * 3600


class ProjectAssetResolver:
    """Resolves ``ast_…`` ids within one project; URLs through the SSRF-safe fetcher."""

    def __init__(self, project: Project, allow_fetch: bool = True) -> None:
        self.project = project
        self.allow_fetch = allow_fetch
        self._refs: dict[str, ImageRef | None] = {}

    def image(self, asset_id: str) -> ImageRef | None:
        if asset_id in self._refs:
            return self._refs[asset_id]
        ref = None
        try:
            uid = ids.decode("ast", asset_id)
        except ids.InvalidId:
            uid = None
        if uid is not None:
            asset = (
                Asset.objects.filter(project=self.project, id=uid, deleted_at__isnull=True)
                .only("id", "path", "width_px", "height_px")
                .first()
            )
            if asset is not None:
                path = store().path(asset.path)
                if path.exists():
                    ref = ImageRef(
                        key=asset.path,
                        path=str(path),
                        width=asset.width_px or 0,
                        height=asset.height_px or 0,
                        vector=asset.path.endswith(".svg"),
                    )
        self._refs[asset_id] = ref
        return ref

    def fetch(self, src: str) -> ImageRef | None:
        if src.startswith("data:"):
            data = decode_data_uri(src)
            if data is None:
                return None
            w, h = image_size(data=data)
            return ImageRef(key="data:" + hashlib.sha256(data).hexdigest()[:24], data=data, width=w, height=h, vector=looks_like_svg(data=data))
        if not self.allow_fetch:
            return None
        cache_dir = Path(settings.SNAPFILE_CACHE_DIR) / "images"
        digest = hashlib.sha256(src.encode()).hexdigest()
        cached = cache_dir / digest[:2] / digest
        if cached.exists() and time.time() - cached.stat().st_mtime < IMAGE_URL_CACHE_TTL:
            data = cached.read_bytes()
        else:
            try:
                res = request("GET", src, timeout=5.0, max_bytes=10 * 1024 * 1024)
            except FetchError:
                return None
            if res.status != 200 or not res.content_type.startswith("image/"):
                return None
            data = res.data
            cached.parent.mkdir(parents=True, exist_ok=True)
            tmp = cached.with_suffix(".tmp")
            tmp.write_bytes(data)
            tmp.replace(cached)
        try:
            w, h = image_size(path=str(cached))
        except Exception:
            return None
        return ImageRef(key=f"url:{digest[:24]}", path=str(cached), width=w, height=h, vector=looks_like_svg(path=str(cached)))
