
from fastapi import FastAPI,HTTPException
from sqlalchemy.orm import Session
from src.menu_design.apps.projects import models, schemas
from src.menu_design.apps.projects import utils
from typing import List, Union
from sqlalchemy import func
import base64
import os
import uuid
from pathlib import Path



BASE_URL = os.getenv("BASE_URL", "http://localhost:8000/")


# Dynamically resolve root directory and static image save path
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
STATIC_PATH = os.path.join(BASE_DIR, "menu_design", "designer", "static", "template_images")
os.makedirs(STATIC_PATH, exist_ok=True)



def create_project(db: Session, project: schemas.ProjectCreate):
    slug = project.slug or project.name.lower().replace(" ", "-")
    unique_slug = utils.generate_unique_slug(db, slug)
    if not unique_slug:
        raise ValueError("Failed to generate a unique slug")
    try:
        # Parse and decode base64 data
        if "," in project.thumbnail:
            _, data = project.thumbnail.split(",", 1)
        else:
            data = project.thumbnail

        # Determine file extension
        ext = "png"
        if "jpeg" in project.thumbnail or "jpg" in project.thumbnail:
            ext = "jpg"
        elif "gif" in project.thumbnail:
            ext = "gif"

        # Generate a unique filename
        image_filename = f"{uuid.uuid4().hex}.{ext}"
        image_filepath = os.path.join(STATIC_PATH, image_filename)

        # Save the decoded image
        with open(image_filepath, "wb") as f:
            f.write(base64.b64decode(data))
            f.close()

        # Generate the public URL (adjust path if needed)
        full_image_url = f"{BASE_URL}static/template_images/{image_filename}"

        # return {"url": full_image_url}
        project.thumbnail = full_image_url

    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Invalid image data: {str(e)}")
    db_project = models.Project(**project.model_dump(exclude={"slug"}), slug=unique_slug)
    db.add(db_project)
    db.commit()
    db.refresh(db_project)
    return db_project
