"""api.v1.auth — API Key management endpoints."""
from __future__ import annotations
import json
import secrets
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from typing import Optional
from agentpaas.api.deps import get_tenant, get_database
from agentpaas.api.middleware.auth import TenantContext, hash_key
from agentpaas.db.models import Database, gen_id, now_utc

router = APIRouter(prefix="/auth", tags=["auth"])

class CreateKeyRequest(BaseModel):
    name: str = "default"
    scopes: list = Field(default_factory=lambda: ["agents:read", "agents:execute"])
    rate_limit: int = 60
    expires_at: Optional[str] = None

@router.post("/keys", status_code=201)
async def create_api_key(req: CreateKeyRequest, tenant: TenantContext = Depends(get_tenant), db: Database = Depends(get_database)):
    raw_key = f"ap_{secrets.token_hex(16)}"
    key_id = gen_id("key_")
    db.execute(
        "INSERT INTO api_keys (id, tenant_id, user_id, key_hash, key_prefix, name, scopes, rate_limit, expires_at, status, created_at) "
        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?)",
        (key_id, tenant.tenant_id, tenant.user_id, hash_key(raw_key), raw_key[:8],
         req.name, json.dumps(req.scopes), req.rate_limit, req.expires_at, now_utc())
    )
    db.commit()
    return {"key_id": key_id, "api_key": raw_key, "warning": "Store this key securely. It will not be shown again."}

@router.get("/keys")
async def list_keys(tenant: TenantContext = Depends(get_tenant), db: Database = Depends(get_database)):
    keys = db.fetchall("SELECT id, key_prefix, name, scopes, rate_limit, status, last_used_at, created_at FROM api_keys WHERE tenant_id = ?", (tenant.tenant_id,))
    for k in keys:
        k["scopes"] = json.loads(k.get("scopes", "[]"))
    return {"keys": keys}

@router.delete("/keys/{key_id}")
async def revoke_key(key_id: str, tenant: TenantContext = Depends(get_tenant), db: Database = Depends(get_database)):
    db.execute("UPDATE api_keys SET status='revoked' WHERE id = ? AND tenant_id = ?", (key_id, tenant.tenant_id))
    db.commit()
    return {"message": "Key revoked"}
