import os, subprocess
from fastapi import APIRouter, Depends, HTTPException
from core.auth import require_admin

router = APIRouter()
ENV_FILES = [
    "/opt/guardia/app/.env",
    "/opt/manager/backend/.env",
]
SENSITIVE = {"SECRET", "PASSWORD", "KEY", "TOKEN", "PASS", "PWD"}

def _mask(k: str, v: str) -> str:
    return "****" if any(s in k.upper() for s in SENSITIVE) else v

@router.get("/env")
async def get_env(_=Depends(require_admin)):
    result: dict[str, str] = {}
    for path in ENV_FILES:
        try:
            with open(path) as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith("#") and "=" in line:
                        k, _, v = line.partition("=")
                        result[k.strip()] = _mask(k.strip(), v.strip())
        except FileNotFoundError:
            pass
    return result

@router.post("/nginx/reload")
async def nginx_reload(_=Depends(require_admin)):
    test = subprocess.run(["nginx", "-t"], capture_output=True, text=True)
    if test.returncode != 0:
        raise HTTPException(status_code=400, detail=f"설정 오류: {test.stderr[:300]}")
    subprocess.run(["systemctl", "reload", "nginx"])
    return {"message": "Nginx 리로드 완료"}
