# /opt/docker/dev/service_finder/backend/app/services/document_service.py
import os
from PIL import Image
from uuid import uuid4
from fastapi import UploadFile, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.document import Document
from app.core.config import settings

class DocumentService:
    @staticmethod
    async def process_upload(
        file: UploadFile, parent_type: str, parent_id: str, 
        db: AsyncSession, background_tasks: BackgroundTasks
    ):
        """ Kép optimalizálás, Thumbnail generálás és NAS tárolás. """
        file_uuid = str(uuid4())
        ext = file.filename.split('.')[-1].lower() if '.' in file.filename else "webp"
        
        # Útvonalak a settings-ből (vagy fallback)
        nas_base = getattr(settings, "NAS_STORAGE_PATH", "/mnt/nas/app_data")
        vault_dir = os.path.join(nas_base, parent_type, parent_id, "vault")
        thumb_dir = os.path.join(settings.STATIC_DIR, "previews", parent_type, parent_id)
        
        os.makedirs(vault_dir, exist_ok=True)
        os.makedirs(thumb_dir, exist_ok=True)

        content = await file.read()
        temp_path = f"/tmp/{file_uuid}_{file.filename}"
        with open(temp_path, "wb") as f: f.write(content)

        # Képfeldolgozás
        img = Image.open(temp_path)
        
        # Thumbnail (SSD)
        thumb_filename = f"{file_uuid}_thumb.webp"
        thumb_path = os.path.join(thumb_dir, thumb_filename)
        thumb_img = img.copy()
        thumb_img.thumbnail((300, 300))
        thumb_img.save(thumb_path, "WEBP", quality=80)

        # Optimalizált eredeti (NAS)
        vault_filename = f"{file_uuid}.webp"
        vault_path = os.path.join(vault_dir, vault_filename)
        if img.width > 1600:
            img = img.resize((1600, int(img.height * (1600 / img.width))), Image.Resampling.LANCZOS)
        img.save(vault_path, "WEBP", quality=85)

        # Mentés az új Document modellbe
        new_doc = Document(
            id=uuid4(),
            parent_type=parent_type,
            parent_id=parent_id,
            original_name=file.filename,
            file_hash=file_uuid,
            file_ext="webp",
            mime_type="image/webp",
            file_size=os.path.getsize(vault_path),
            has_thumbnail=True,
            thumbnail_path=f"/static/previews/{parent_type}/{parent_id}/{thumb_filename}"
        )
        db.add(new_doc)
        await db.commit()
        os.remove(temp_path)
        return new_doc