"""Export packaging designs naar NAS projectmap."""
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from app.db import execute, fetch_one
from app.services import nas_folders


def _packaging_dir(project_id: int) -> Path | None:
    row = fetch_one(
        """
        SELECT p.id, p.name, p.nas_path, p.client_id, p.project_type, c.name AS client_name
        FROM cockpit_projects p
        LEFT JOIN clients c ON c.id = p.client_id
        WHERE p.id = %s
        """,
        (project_id,),
    )
    if not row:
        return None
    nas_path = row.get("nas_path")
    if not nas_path:
        try:
            paths = nas_folders.ensure_project_folder(
                int(row["id"]),
                row["name"] or f"project-{project_id}",
                row.get("client_id"),
                row.get("client_name"),
                row.get("project_type") or "packaging",
            )
            nas_path = paths.get("nas_path")
        except Exception:
            return None
    root = Path(nas_path) / "packaging"
    root.mkdir(parents=True, exist_ok=True)
    return root


def export_packaging_files(
    packaging_id: str,
    cockpit_project_id: int,
    svg_content: str,
    spec: dict[str, Any],
    png_bytes: bytes | None = None,
    pdf_bytes: bytes | None = None,
) -> dict[str, Any]:
    """Schrijf SVG/PNG/PDF + manifest naar NAS packaging/ submap."""
    root = _packaging_dir(cockpit_project_id)
    if not root:
        return {"ok": False, "error": "Geen NAS-map voor project"}

    design_name = spec.get("design_name") or spec.get("text", {}).get("product_name") or packaging_id[:8]
    slug = nas_folders.slugify(str(design_name))[:32]
    base = f"{packaging_id[:8]}-{slug}"

    paths: dict[str, str] = {}
    svg_path = root / f"{base}.svg"
    svg_path.write_text(svg_content, encoding="utf-8")
    paths["svg"] = str(svg_path)

    if png_bytes:
        png_path = root / f"{base}.png"
        png_path.write_bytes(png_bytes)
        paths["png"] = str(png_path)

    if pdf_bytes:
        pdf_path = root / f"{base}.pdf"
        pdf_path.write_bytes(pdf_bytes)
        paths["pdf"] = str(pdf_path)

    manifest = {
        "packaging_id": packaging_id,
        "design_name": design_name,
        "spec": spec,
        "files": paths,
    }
    manifest_path = root / f"{base}.json"
    manifest_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
    paths["manifest"] = str(manifest_path)

    primary = paths.get("pdf") or paths.get("svg")
    execute(
        """
        UPDATE project_assets SET file_path = %s
        WHERE project_id = %s AND asset_type = 'packaging' AND ref_id = %s
        """,
        (primary, cockpit_project_id, packaging_id),
    )

    return {"ok": True, "nas_packaging_dir": str(root), "files": paths}
