"""Brief HTML deployment to the VPS webroot.

Writes `<slug>.html` to the bind-mounted `BRIEF_OUTPUT_DIR` so it is served by
the VPS nginx under `https://just2done.com/brief/`. No `scp` / `rsync` over the
wire: in production this volume is `--volume /var/www/just2done.com/brief:/brief-output`
and we simply drop a UTF-8 file.

Idempotent — re-running with the same slug atomically replaces the file.
"""

from __future__ import annotations

import logging
import os
import tempfile
from pathlib import Path

from app.config import settings

logger = logging.getLogger(__name__)


class DeploymentError(RuntimeError):
    pass


async def deploy_brief_html(*, slug: str, html: str) -> str:
    """Write `html` to `<BRIEF_OUTPUT_DIR>/<slug>.html` (atomic write).

    Returns the *absolute path of the file on disk* (inside the container).
    Public URL is built by the orchestrator from `PUBLIC_BASE_URL + '/' + slug`.
    """
    directory = Path(settings.BRIEF_OUTPUT_DIR).resolve()
    directory.mkdir(parents=True, exist_ok=True)
    target = directory / f"{slug}.html"

    if not html or not html.strip():
        raise DeploymentError("refusing to deploy empty HTML")

    try:
        # Atomic: write to '<target>.tmp.pid' then rename over the existing file.
        fd, tmp_path = tempfile.mkstemp(prefix=f"{target.name}.", suffix=".tmp", dir=str(directory))
        try:
            with os.fdopen(fd, "w", encoding="utf-8") as fh:
                fh.write(html)
            os.chmod(tmp_path, 0o644)
            os.replace(tmp_path, target)
        finally:
            if os.path.exists(tmp_path):
                os.remove(tmp_path)
    except OSError as exc:
        raise DeploymentError(f"failed to write {target}: {exc}") from exc

    logger.info("deployed brief html -> %s", target)
    return str(target)