from __future__ import annotations

from typing import Any

SAMPLE_INPUT_CONTEXT = {
    "project": "AI civil service capability",
    "country": "Kazakhstan",
    "timeframe": "2026-2027",
}


AGENT_OPENAPI_EXAMPLES: dict[tuple[str, str], dict[str, Any]] = {
    ("post", "/agents/register"): {
        "agent_sandbox_registration": {
            "summary": "Register a sandbox workflow agent",
            "value": {
                "agent_name": "proposal-worker",
                "agent_type": "workflow_agent",
                "purpose": "Run deterministic GrantFlow smoke workflows",
            },
        }
    },
    ("post", "/agents/onboarding"): {
        "self_serve_api_key": {
            "summary": "Request self-serve sandbox API-key onboarding",
            "value": {
                "agent_name": "proposal-worker",
                "auth_type": "api_key",
                "requested_scopes": ["generate:write", "status:read", "quality:read"],
                "purpose": "Autonomously run GrantFlow sandbox workflows",
            },
        },
        "oauth_client_credentials": {
            "summary": "Request OAuth client-credentials onboarding",
            "value": {
                "agent_name": "enterprise-proposal-agent",
                "auth_type": "oauth_client_credentials",
                "requested_tenant_id": "tenant_alpha",
                "requested_scopes": ["generate:write", "status:read", "quality:read", "export:write"],
            },
        },
    },
    ("post", "/agents/oauth/token"): {
        "client_credentials_token": {
            "summary": "Exchange self-serve OAuth client credentials for a Bearer access token",
            "value": {
                "grant_type": "client_credentials",
                "client_id": "gf_client_agent_enterprise_proposal_agent",
                "client_secret": "gf_oauth_client_<returned-once>",
                "scope": "generate:write status:read quality:read",
                "ttl_seconds": 3600,
            },
        }
    },
    ("post", "/agents/credentials/rotate"): {
        "rotate_self_serve_agent_key": {
            "summary": "Rotate a self-serve API key or OAuth client secret",
            "value": {
                "credential": "gf_agent_<current-token>",
                "ttl_seconds": 3600,
            },
        }
    },
    ("post", "/agents/credentials/revoke"): {
        "revoke_self_serve_credential": {
            "summary": "Revoke a self-serve API key, Bearer token, or OAuth client secret",
            "value": {
                "credential": "gf_agent_<current-token>",
                "reason": "credential rotation completed",
            },
        }
    },
    ("post", "/agents/session"): {
        "short_lived_runtime_session": {
            "summary": "Create a short-lived runtime credential after onboarding",
            "value": {
                "agent_id": "agent_proposal_worker",
                "tenant_id": "sandbox_proposal_worker",
                "requested_scopes": ["generate:write", "status:read", "quality:read"],
                "ttl_seconds": 3600,
            },
        }
    },
    ("post", "/agents/introspect"): {
        "introspect_configured_api_key": {
            "summary": "Validate X-API-Key and read active tenant/scope claims",
            "value": {},
        }
    },
    ("post", "/generate/preflight"): {
        "agent_preflight": {
            "summary": "Agent readiness check before generation",
            "value": {
                "donor_id": "usaid",
                "tenant_id": "sandbox_proposal_worker",
                "architect_rag_enabled": False,
                "input_context": SAMPLE_INPUT_CONTEXT,
                "client_metadata": {"agent_id": "agent_proposal_worker"},
            },
        }
    },
    ("post", "/generate"): {
        "agent_generation": {
            "summary": "Start deterministic agent generation",
            "value": {
                "donor_id": "usaid",
                "tenant_id": "sandbox_proposal_worker",
                "request_id": "agent_proposal_worker:sandbox-generate-001",
                "input_context": SAMPLE_INPUT_CONTEXT,
                "llm_mode": False,
                "architect_rag_enabled": False,
                "hitl_enabled": False,
                "strict_preflight": False,
                "client_metadata": {"agent_id": "agent_proposal_worker"},
            },
        }
    },
}


AGENT_RECIPES = [
    {
        "name": "sandbox_generate",
        "description": "Register or onboard an agent, run preflight, generate, poll status, inspect quality and events.",
        "steps": [
            {"method": "POST", "path": "/agents/onboarding", "tool": "grantflow_onboard_agent"},
            {"method": "POST", "path": "/agents/session", "tool": "grantflow_create_session"},
            {"method": "POST", "path": "/agents/introspect", "tool": "grantflow_introspect_agent"},
            {"method": "POST", "path": "/generate/preflight", "tool": "grantflow_run_preflight"},
            {"method": "POST", "path": "/generate", "tool": "grantflow_start_generation"},
            {"method": "GET", "path": "/status/{job_id}", "tool": "grantflow_get_status"},
            {"method": "GET", "path": "/status/{job_id}/quality", "tool": "grantflow_get_quality"},
            {"method": "GET", "path": "/status/{job_id}/events", "tool": "grantflow_get_events"},
        ],
    },
    {
        "name": "agent_credential_rotation",
        "description": "Rotate a credential, validate the replacement, then revoke credentials that should no longer be used.",
        "steps": [
            {"method": "POST", "path": "/agents/introspect", "tool": "grantflow_introspect_agent"},
            {"method": "POST", "path": "/agents/credentials/rotate", "tool": "grantflow_rotate_credential"},
            {"method": "POST", "path": "/agents/introspect", "tool": "grantflow_introspect_agent"},
            {"method": "POST", "path": "/agents/credentials/revoke", "tool": "grantflow_revoke_credential"},
        ],
    },
    {
        "name": "grant_lifecycle_export",
        "description": "Run preflight, generate, wait for terminal status, inspect quality/events, then export only after review gates.",
        "steps": [
            {"method": "POST", "path": "/generate/preflight", "tool": "grantflow_run_preflight"},
            {"method": "POST", "path": "/generate", "tool": "grantflow_start_generation"},
            {"method": "GET", "path": "/status/{job_id}", "tool": "grantflow_get_status"},
            {"method": "GET", "path": "/status/{job_id}/quality", "tool": "grantflow_get_quality"},
            {"method": "GET", "path": "/status/{job_id}/events", "tool": "grantflow_get_events"},
            {"method": "POST", "path": "/export", "requires_operator_policy": True},
        ],
    },
    {
        "name": "production_oauth_client_credentials",
        "description": "Use /agents/onboarding to request OAuth client metadata, then exchange client credentials for a Bearer token.",
        "steps": [
            {"method": "POST", "path": "/agents/onboarding"},
            {"method": "POST", "path": "/agents/oauth/token"},
            {"method": "POST", "path": "/agents/introspect"},
            {"method": "POST", "path": "/generate/preflight"},
            {"method": "POST", "path": "/generate"},
        ],
    },
]


def install_agent_openapi_examples(schema: dict[str, Any]) -> None:
    schema["x-grantflow-agent-recipes"] = AGENT_RECIPES
    paths = schema.get("paths") or {}
    for (method, path), examples in AGENT_OPENAPI_EXAMPLES.items():
        operation = (paths.get(path) or {}).get(method)
        if not isinstance(operation, dict):
            continue
        content = operation.setdefault("requestBody", {}).setdefault("content", {}).setdefault("application/json", {})
        content["examples"] = examples
