from pathlib import Path
from app.core.config import get_settings
from app.utils.image import safe_delete

settings = get_settings()

PROJECT_ROOT: Path = settings.PROJECT_BASE_DIR
ASSETS_ROOT: Path = (PROJECT_ROOT / "assets").resolve()

PROJECTS_BASE: Path = (PROJECT_ROOT / settings.PROJECTS_ASSETS_DIRECTORY).resolve()
PROJECTS_BASE.mkdir(parents=True, exist_ok=True)


# Project folder structure helpers
def project_dir(project_id: int) -> Path:
    return PROJECTS_BASE / f"project_{project_id}"

def overlay_dir(project_id: int) -> Path:
    return project_dir(project_id) / "overlay_images"

def overlay_thumb_dir(project_id: int) -> Path:
    return overlay_dir(project_id) / "thumbnail"

def logo_dir(project_id: int) -> Path:
    return project_dir(project_id) / "logo_images"

def logo_thumb_dir(project_id: int) -> Path:
    return logo_dir(project_id) / "thumbnail"

def final_dir(project_id: int) -> Path:
    return project_dir(project_id) / "final_images"

def final_thumb_dir(project_id: int) -> Path:
    return final_dir(project_id) / "thumbnail"


# Path conversion helpers
def rel_path(p: Path | None) -> str | None:
    if p is None:
        return None
    try:
        rel = p.resolve().relative_to(ASSETS_ROOT.resolve())
        return str(Path("assets") / rel).replace("\\", "/")
    except Exception:
        s = str(p).replace("\\", "/")
        if "/assets/" in s:
            return "assets/" + s.split("/assets/")[-1]
        return s

def abs_from_db(path_str: str | None) -> Path | None:
    if not path_str:
        return None

    clean = path_str.replace("\\", "/").lstrip("/")
    while clean.startswith("assets/"):
        clean = clean[len("assets/"):]
    return (ASSETS_ROOT / clean).resolve()

# Cleanup helper
def cleanup_relative(path_str: str | None):
    """
    Delete stored DB path (relative inside assets/).
    """
    p = abs_from_db(path_str)
    if p:
        safe_delete(p)
