"""HTTP dependencies shared by Agent endpoints."""
from __future__ import annotations

import hashlib
import hmac
from typing import Optional

from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from ..models import TestHost


def agent_token_digest(token: str) -> str:
    return hashlib.sha256(token.encode("utf-8")).hexdigest()


def bearer_token(authorization: Optional[str]) -> str:
    scheme, separator, value = (authorization or "").partition(" ")
    if not separator or scheme.lower() != "bearer" or not value.strip():
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Agent bearer token 缺失",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return value.strip()


async def require_agent(
    session: AsyncSession,
    agent_id: str,
    authorization: Optional[str],
) -> TestHost:
    host = await session.scalar(select(TestHost).where(TestHost.agent_id == agent_id))
    token = bearer_token(authorization)
    if (
        host is None
        or not host.agent_token
        or not hmac.compare_digest(host.agent_token, agent_token_digest(token))
    ):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Agent 身份无效",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return host
