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

router = APIRouter()

ALLOWED_SVCS = {
    "nginx", "zioinfo", "zioinfo-deploy", "guardia", "guardia-manager",
    "gitea", "jenkins", "postgresql", "ollama",
}

@router.get("/resources")
async def resources(_=Depends(verify_token)):
    try:
        import psutil
        cpu  = psutil.cpu_percent(interval=0.2)
        mem  = psutil.virtual_memory()
        disk = psutil.disk_usage("/")
        return {
            "cpu_percent": round(cpu, 1),
            "memory": {"total_gb": round(mem.total/1e9,1), "used_gb": round(mem.used/1e9,1), "percent": mem.percent},
            "disk":   {"total_gb": round(disk.total/1e9,1),"used_gb": round(disk.used/1e9,1), "percent": disk.percent},
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/services")
async def services(_=Depends(verify_token)):
    result: dict[str, str] = {}
    for svc in ALLOWED_SVCS:
        p = subprocess.run(["systemctl", "is-active", svc], capture_output=True, text=True)
        result[svc] = p.stdout.strip()
    return result

@router.post("/services/{name}/restart")
async def restart(name: str, admin=Depends(require_admin)):
    if name not in ALLOWED_SVCS:
        raise HTTPException(status_code=400, detail="허용되지 않은 서비스")
    p = subprocess.run(["systemctl", "restart", name], capture_output=True, text=True)
    if p.returncode != 0:
        raise HTTPException(status_code=500, detail=p.stderr[:300])
    return {"message": f"{name} 재시작 완료"}
