"""tkuser API 프록시 클라이언트 — tkeg"""
import httpx
import os
from typing import Optional
from fastapi import HTTPException, Request

TKUSER_API_URL = os.getenv("TKUSER_API_URL", "http://tkuser-api:3000")


def get_token_from_request(request: Request) -> str:
    auth = request.headers.get("Authorization", "")
    if auth.startswith("Bearer "):
        return auth[7:]
    return request.cookies.get("sso_token", "")


def _headers(token: str) -> dict:
    if not token:
        raise HTTPException(status_code=401, detail="인증 토큰이 필요합니다.")
    return {"Authorization": f"Bearer {token}"}


def _map_project(data: dict) -> dict:
    return {
        "id": data.get("project_id"),
        "job_no": data.get("job_no"),
        "project_name": data.get("project_name"),
        "client_name": data.get("client_name"),
        "is_active": data.get("is_active", True),
        "created_at": data.get("created_at"),
    }


async def get_projects(token: str, active_only: bool = True) -> list:
    endpoint = "/api/projects/active" if active_only else "/api/projects"
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get(f"{TKUSER_API_URL}{endpoint}", headers=_headers(token))
        if resp.status_code != 200:
            raise HTTPException(status_code=resp.status_code, detail="프로젝트 목록 조회 실패")
        body = resp.json()
        if not body.get("success"):
            raise HTTPException(status_code=500, detail=body.get("error", "알 수 없는 오류"))
        return [_map_project(p) for p in body.get("data", [])]


async def get_project(token: str, project_id: int) -> Optional[dict]:
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get(f"{TKUSER_API_URL}/api/projects/{project_id}", headers=_headers(token))
        if resp.status_code == 404:
            return None
        if resp.status_code != 200:
            raise HTTPException(status_code=resp.status_code, detail="프로젝트 조회 실패")
        body = resp.json()
        if not body.get("success"):
            raise HTTPException(status_code=500, detail=body.get("error", "알 수 없는 오류"))
        return _map_project(body.get("data"))
