import httpx, os
from fastapi import APIRouter, Depends, HTTPException
from core.auth import verify_token

router = APIRouter()
WEBHOOK_URL  = os.environ.get("DEPLOY_WEBHOOK", "http://localhost:9999/")
DEPLOY_LOG   = os.environ.get("DEPLOY_LOG",     "/var/log/zioinfo/deploy.log")

@router.post("/trigger/{repo}")
async def trigger(repo: str, user=Depends(verify_token)):
    async with httpx.AsyncClient() as c:
        try:
            r = await c.post(WEBHOOK_URL,
                json={"repo": repo, "triggered_by": user.get("sub", "manager")},
                timeout=10)
            return {"status": r.status_code, "message": f"{repo} 배포 트리거됨"}
        except Exception as e:
            raise HTTPException(status_code=502, detail=f"Deploy Webhook 연결 실패: {e}")

@router.get("/history")
async def history(_=Depends(verify_token)):
    try:
        with open(DEPLOY_LOG, encoding="utf-8", errors="replace") as f:
            lines = f.readlines()[-200:]
        return {"lines": [l.rstrip() for l in lines]}
    except FileNotFoundError:
        return {"lines": []}
