"""Autenticacion de Hardware Agents por API Key (Bearer token)."""
import secrets
from fastapi import Depends, HTTPException, Header
from sqlalchemy.orm import Session as DBSession
from database import get_db
from models import Agent


def generate_token():
    """Genera un token unico de 32 caracteres."""
    return secrets.token_hex(16)


def require_agent_token(
    authorization: str = Header(None),
    db: DBSession = Depends(get_db),
) -> Agent:
    """
    Dependency de FastAPI: valida el Bearer token y retorna el Agent.
    Uso: agent = Depends(require_agent_token)
    """
    if not authorization:
        raise HTTPException(status_code=401, detail="Header Authorization requerido")

    # Extraer token del header "Bearer <token>"
    parts = authorization.split(" ")
    if len(parts) != 2 or parts[0].lower() != "bearer":
        raise HTTPException(status_code=401, detail="Formato: Authorization: Bearer <token>")

    token = parts[1]

    # Buscar agent por token
    agent = db.query(Agent).filter(Agent.token == token).first()
    if not agent:
        raise HTTPException(status_code=403, detail="Token invalido")

    return agent
