File size: 2,818 Bytes
71b4454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
Production deployment-settings route.
GET  /api/deploy/settings  — returns current deployment configuration
POST /api/deploy/settings  — updates deployment configuration
"""
from __future__ import annotations

import json
import logging
import os
from pathlib import Path
from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

logger = logging.getLogger("dolor3v.deploy.settings")

router = APIRouter(prefix="/api/deploy", tags=["deploy"])

SETTINGS_FILE = Path(os.environ.get("DEPLOY_SETTINGS_PATH", "/tmp/deploy_settings.json"))

DEFAULTS: dict[str, Any] = {
    "target": os.environ.get("DEPLOY_TARGET", "cloudflare"),
    "cloudflare_account_id": os.environ.get("CLOUDFLARE_ACCOUNT_ID", ""),
    "cloudflare_api_token": "",
    "render_service_id": os.environ.get("RENDER_SERVICE_ID", ""),
    "hf_space": os.environ.get("HF_SPACE", "Daviddolor/Travelerdev"),
    "auto_deploy": False,
    "build_command": "npm run build",
    "output_dir": ".next",
    "environment": os.environ.get("ENVIRONMENT", "production"),
    "backend_url": os.environ.get(
        "TRAVELER_BACKEND_URL",
        os.environ.get("NEXT_PUBLIC_BACKEND_URL", ""),
    ),
}


def _load() -> dict[str, Any]:
    if SETTINGS_FILE.exists():
        try:
            return {**DEFAULTS, **json.loads(SETTINGS_FILE.read_text())}
        except Exception:
            pass
    return dict(DEFAULTS)


def _save(data: dict[str, Any]) -> None:
    SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
    SETTINGS_FILE.write_text(json.dumps(data, indent=2))


class DeploySettingsUpdate(BaseModel):
    target: str | None = None
    cloudflare_account_id: str | None = None
    cloudflare_api_token: str | None = None
    render_service_id: str | None = None
    hf_space: str | None = None
    auto_deploy: bool | None = None
    build_command: str | None = None
    output_dir: str | None = None
    environment: str | None = None
    backend_url: str | None = None


@router.get("/settings")
async def get_deploy_settings() -> dict[str, Any]:
    """Return current deployment configuration (secrets redacted)."""
    settings = _load()
    redacted = {**settings}
    if redacted.get("cloudflare_api_token"):
        redacted["cloudflare_api_token"] = "***"
    return {"success": True, "settings": redacted}


@router.post("/settings")
async def update_deploy_settings(body: DeploySettingsUpdate) -> dict[str, Any]:
    """Persist deployment configuration updates."""
    current = _load()
    updates = body.model_dump(exclude_none=True)
    current.update(updates)
    try:
        _save(current)
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Failed to persist settings: {exc}") from exc
    return {"success": True, "updated": list(updates.keys())}