#!/usr/bin/env python3
"""BSD PDF Watermark Studio — local glassmorphism UI backend."""

from __future__ import annotations

import os
import sys
import uuid
from datetime import date
from pathlib import Path

from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles

# --- paths: source tree OR frozen PyInstaller bundle ---
_RES = Path(os.environ.get("BSD_WM_RESOURCE", "")).resolve() if os.environ.get("BSD_WM_RESOURCE") else None
_DATA = Path(os.environ.get("BSD_WM_DATA", "")).resolve() if os.environ.get("BSD_WM_DATA") else None

if _RES and _RES.exists():
    ROOT = _RES
    WEB = _RES / "web" if (_RES / "web").exists() else _RES
else:
    WEB = Path(__file__).resolve().parent
    ROOT = WEB.parent

if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from watermark_pdf import process_pdf  # noqa: E402

STATIC = WEB / "static"
if not STATIC.exists():
    STATIC = ROOT / "static"

DATA = _DATA if (_DATA and _DATA.exists()) else ROOT
UPLOADS = DATA / "uploads"
OUTPUTS = DATA / "outputs"
UPLOADS.mkdir(parents=True, exist_ok=True)
OUTPUTS.mkdir(parents=True, exist_ok=True)

app = FastAPI(title="BSD Watermark Studio", version="1.1")
app.mount("/static", StaticFiles(directory=str(STATIC)), name="static")


@app.get("/", response_class=HTMLResponse)
async def index():
    index_path = STATIC / "index.html"
    if not index_path.exists():
        return HTMLResponse("<h1>BSD Watermark Studio</h1><p>static/index.html missing</p>", status_code=500)
    return index_path.read_text(encoding="utf-8")


@app.get("/favicon.png")
async def favicon():
    fav = STATIC / "assets" / "favicon.png"
    if fav.exists():
        return FileResponse(fav)
    raise HTTPException(404)


@app.post("/api/watermark")
async def watermark(
    file: UploadFile = File(...),
    text: str = Form("BSD CLASS LICENSE"),
    buyer: str = Form("LICENSED USER"),
    order: str = Form("N/A"),
    opacity: float = Form(0.10),
    step: float = Form(110),
    legal_lang: str = Form("ko"),
    no_legal: str = Form("false"),
):
    if not file.filename or not file.filename.lower().endswith(".pdf"):
        raise HTTPException(400, "PDF 파일만 업로드할 수 있습니다.")

    job = uuid.uuid4().hex[:12]
    safe_name = Path(file.filename).name.replace(" ", "_")
    in_path = UPLOADS / f"{job}_{safe_name}"
    out_name = f"{Path(safe_name).stem}_BSD_watermarked.pdf"
    out_path = OUTPUTS / f"{job}_{out_name}"
    skip_legal = str(no_legal).lower() in ("true", "1", "on", "yes")

    data = await file.read()
    if len(data) < 100:
        raise HTTPException(400, "파일이 비어 있거나 너무 작습니다.")
    if len(data) > 80 * 1024 * 1024:
        raise HTTPException(400, "파일 크기 제한: 80MB")
    in_path.write_bytes(data)

    try:
        info = process_pdf(
            in_path,
            out_path,
            text=(text or "BSD CLASS LICENSE").strip(),
            buyer=buyer or "LICENSED USER",
            order=order or "N/A",
            issued=date.today().isoformat(),
            opacity=float(opacity),
            fontsize=26,
            step=max(70.0, min(float(step), 220.0)),
            add_legal=not skip_legal,
            legal_lang=legal_lang if legal_lang in ("ko", "en", "both") else "ko",
        )
    except Exception as e:
        raise HTTPException(500, f"처리 실패: {e}") from e

    return {
        "ok": True,
        "pages": info["pages"],
        "legal_pages": info["legal_pages_1based"],
        "download": f"/api/download/{job}_{out_name}",
        "filename": out_name,
        "mark": text,
    }


@app.get("/api/download/{filename}")
async def download(filename: str):
    name = Path(filename).name
    path = OUTPUTS / name
    if not path.exists():
        raise HTTPException(404, "파일을 찾을 수 없습니다.")
    return FileResponse(
        path,
        media_type="application/pdf",
        filename=name.split("_", 1)[-1] if "_" in name else name,
    )
