//! HTTP API for Episteme (StemeDB).
//!
//! This crate provides a RESTful HTTP API using axum and utoipa for OpenAPI documentation.
//!
//! # Architecture
//!
//! The API follows the standard axum pattern:
//! - **DTOs** (`dto.rs`) - JSON request/response types with hex-encoded binary data
//! - **Handlers** (`handlers/`) - Thin HTTP handlers that delegate to underlying engines
//! - **State** (`state.rs`) - Shared application state (Journal, Store, QueryEngine)
//! - **Router** (`router()`) - axum router with OpenAPI support via utoipa-axum
//!
//! # Write Path
//!
//! POST /v1/assert → DTO → Assertion → serialize → append to WAL → return hash
//!
//! # Read Path
//!
//! GET /v1/query → QueryParams → Query → QueryEngine → Lens (optional) → DTOs
//!
//! # Example
//!
//! ```ignore
//! use stemedb_api::{create_router, AppState};
//!
//! let state = AppState::new(write_journal, read_journal, store);
//! let app = create_router(state);
//!
//! axum::Server::bind(&addr).serve(app.into_make_service()).await?;
//! ```

pub mod bootstrap;
pub mod dto;
pub mod error;
pub mod handlers;
pub mod hex;
pub mod middleware;
mod routers;
#[cfg(feature = "aphoria")]
pub mod scan_cache;
pub mod services;
pub mod state;

use utoipa::OpenApi;

pub use bootstrap::{
    bootstrap_root_api_key, is_auth_enabled, is_auth_require_all, AUTH_ENABLED_ENV,
    AUTH_REQUIRE_ALL_ENV, ROOT_API_KEY_ENV,
};
pub use error::{ApiError, Result};
pub use middleware::{
    AdmissionLayer, AdmissionService, ApiKeyAuthConfig, ApiKeyAuthLayer, CircuitBreakerLayer,
    CircuitBreakerService, MeterLayer, MeterService,
};
pub use routers::{
    create_router, create_router_full_protection, create_router_full_protection_config,
    create_router_with_admission, create_router_with_auth, create_router_with_auth_config,
    create_router_with_circuit_breaker, create_router_with_meter,
};
pub use state::AppState;

// Re-export the path items for OpenAPI
use handlers::{
    admin::__path_decay_trust_ranks,
    admission::__path_get_admission_status,
    api_keys::{
        __path_create_api_key, __path_list_api_keys, __path_revoke_api_key, __path_rotate_api_key,
        __path_update_api_key,
    },
    assert::__path_create_assertion,
    audit::{__path_get_audit, __path_list_audits},
    circuit_breaker::{
        __path_get_circuit_status, __path_list_tripped_circuits, __path_reset_circuit,
    },
    concepts::{
        __path_create_alias, __path_delete_alias, __path_list_aliases, __path_parse_concept_path,
        __path_resolve_alias, __path_suggest_aliases,
    },
    constraints::__path_constraints_query,
    epoch::__path_create_epoch,
    escalation::{__path_list_escalations, __path_resolve_escalation},
    gold_standard::{
        __path_create_gold_standard, __path_list_gold_standards, __path_remove_gold_standard,
        __path_verify_agent,
    },
    health::__path_health_check,
    layered::__path_layered_query,
    meter::{__path_get_quota_status, __path_set_quota_limit},
    quarantine::{
        __path_approve_quarantine, __path_get_quarantine, __path_list_quarantine,
        __path_reject_quarantine,
    },
    query::__path_query_assertions,
    skeptic::__path_skeptic_query,
    source::{__path_get_provenance, __path_store_source},
    source_registry::{
        __path_export_source_impact, __path_get_source, __path_get_source_impact,
        __path_list_sources, __path_quarantine_source, __path_register_source,
        __path_restore_source, __path_update_source_status,
    },
    supersede::__path_supersede,
    trace::__path_trace,
    vote::__path_create_vote,
};

/// OpenAPI documentation schema.
#[derive(OpenApi)]
#[openapi(
    paths(
        get_admission_status,
        create_assertion,
        create_epoch,
        create_vote,
        query_assertions,
        skeptic_query,
        layered_query,
        constraints_query,
        health_check,
        list_audits,
        get_audit,
        trace,
        supersede,
        get_quota_status,
        set_quota_limit,
        store_source,
        get_provenance,
        decay_trust_ranks,
        list_escalations,
        resolve_escalation,
        create_gold_standard,
        list_gold_standards,
        remove_gold_standard,
        verify_agent,
        create_alias,
        resolve_alias,
        delete_alias,
        list_aliases,
        suggest_aliases,
        parse_concept_path,
        // Quarantine (Content Defense Phase 7C)
        list_quarantine,
        get_quarantine,
        approve_quarantine,
        reject_quarantine,
        // Circuit Breakers (Phase 7D)
        get_circuit_status,
        reset_circuit,
        list_tripped_circuits,
        // Source Registry (P3.1, P3.2)
        register_source,
        get_source,
        update_source_status,
        list_sources,
        get_source_impact,
        quarantine_source,
        restore_source,
        export_source_impact,
        // API Key Management (P4.2)
        create_api_key,
        list_api_keys,
        revoke_api_key,
        rotate_api_key,
        update_api_key,
    ),
    components(
        schemas(
            dto::CreateAssertionRequest,
            dto::CreateVoteRequest,
            dto::CreateEpochRequest,
            dto::QueryParams,
            dto::AssertionResponse,
            dto::QueryResponse,
            dto::CreateResponse,
            dto::ErrorResponse,
            dto::HealthResponse,
            dto::ObjectValueDto,
            dto::LifecycleDto,
            dto::SupersessionTypeDto,
            dto::LensDto,
            dto::SignatureDto,
            dto::AuditQueryParams,
            dto::QueryAuditResponse,
            dto::QueryAuditListResponse,
            dto::QueryParamsAuditDto,
            dto::ContributingAssertionDto,
            dto::TraceParams,
            dto::TraceResponse,
            dto::SupersedeRequest,
            dto::SupersedeResponse,
            dto::SkepticQueryParams,
            dto::SkepticResponse,
            dto::ResolutionStatusDto,
            dto::ClaimSummaryDto,
            dto::SourceSummaryDto,
            dto::AgentSummaryDto,
            dto::SourceClassDto,
            dto::TierResolutionDto,
            dto::LayeredQueryResponse,
            dto::ConstraintsQueryParams,
            dto::ConstraintsResponse,
            dto::ConstraintEntryDto,
            handlers::meter::QuotaStatusResponse,
            handlers::meter::SetQuotaLimitRequest,
            handlers::meter::SetQuotaLimitResponse,
            dto::StoreSourceRequest,
            dto::StoreSourceResponse,
            dto::ProvenanceResponse,
            dto::DecayTrustRanksRequest,
            dto::DecayTrustRanksResponse,
            dto::EscalationEventDto,
            dto::EscalationLevelDto,
            dto::EscalationListResponse,
            dto::CreateGoldStandardRequest,
            dto::CreateGoldStandardResponse,
            dto::GoldStandardDto,
            dto::GoldStandardListResponse,
            dto::VerifyAgentRequest,
            dto::VerificationResult,
            dto::CreateAliasRequest,
            dto::AliasResponse,
            dto::DeleteAliasRequest,
            dto::DeleteAliasResponse,
            dto::ResolveAliasParams,
            dto::ResolveAliasResponse,
            dto::ListAliasesParams,
            dto::ListAliasesResponse,
            dto::AliasMapping,
            dto::AliasOriginDto,
            dto::AliasSuggestion,
            dto::SuggestAliasesResponse,
            dto::ConceptPathInfo,
            // Admission control
            dto::AdmissionStatusResponse,
            dto::TrustTierDto,
            handlers::admission::AdmissionStatusParams,
            // Quarantine (Content Defense Phase 7C)
            dto::QuarantineEventDto,
            dto::QuarantineReasonDto,
            dto::ContentQualityDto,
            dto::QuarantineListResponse,
            dto::QuarantineGetResponse,
            dto::QuarantineApproveResponse,
            dto::QuarantineListParams,
            // Circuit Breakers (Phase 7D)
            dto::CircuitBreakerStatusResponse,
            dto::CircuitStateDto,
            dto::FailureTypeDto,
            dto::FailureEventDto,
            dto::FailureCountsDto,
            dto::ResetCircuitRequest,
            dto::ResetCircuitResponse,
            dto::TrippedCircuitsResponse,
            dto::TrippedCircuitsParams,
            // Source Registry (P3.1, P3.2)
            dto::RegisterSourceRequest,
            dto::RegisterSourceResponse,
            dto::SourceRecordDto,
            dto::UpdateSourceStatusRequest,
            dto::UpdateSourceStatusResponse,
            dto::ListSourcesParams,
            dto::ListSourcesResponse,
            dto::SourceImpactResponse,
            dto::QuarantineSourceRequest,
            dto::QuarantineSourceResponse,
            dto::RestoreSourceRequest,
            dto::RestoreSourceResponse,
            dto::ExportImpactParams,
            dto::ImpactExportRow,
            dto::SourceWarningDto,
            // API Key Management (P4.2)
            dto::CreateApiKeyRequest,
            dto::CreateApiKeyResponse,
            dto::ApiKeyInfo,
            dto::ListApiKeysResponse,
            dto::RevokeApiKeyResponse,
            dto::RotateApiKeyResponse,
            dto::UpdateApiKeyRequest,
            dto::UpdateApiKeyResponse,
        )
    ),
    tags(
        (name = "assertions", description = "Create and manage assertions"),
        (name = "epochs", description = "Create and manage epochs (paradigms)"),
        (name = "votes", description = "Create votes on assertions"),
        (name = "query", description = "Query assertions with filters and lenses"),
        (name = "health", description = "Health check endpoint"),
        (name = "audit", description = "Query audit trail for incident investigation"),
        (name = "supersession", description = "Supersede assertions for error correction"),
        (name = "meter", description = "Economic throttling and quota management"),
        (name = "provenance", description = "Source document storage and retrieval"),
        (name = "admin", description = "Administrative operations for system maintenance"),
        (name = "concepts", description = "ConceptPath and alias management for cross-scheme resolution"),
        (name = "admission", description = "Admission control and PoW requirements"),
        (name = "quarantine", description = "Content defense quarantine management"),
        (name = "circuit_breaker", description = "Per-agent circuit breaker management"),
        (name = "source-registry", description = "Source metadata registry and impact analysis"),
    ),
    info(
        title = "Episteme (StemeDB) API",
        version = env!("CARGO_PKG_VERSION"),
        description = "HTTP API for the probabilistic knowledge graph",
        contact(
            name = "Episteme Project",
        )
    )
)]
pub(crate) struct ApiDoc;

/// OpenAPI documentation for Aphoria endpoints (feature-gated).
#[cfg(feature = "aphoria")]
mod aphoria_openapi {
    use super::*;

    // Re-export the path items for OpenAPI from the submodules
    use handlers::aphoria::policy::{__path_bless, __path_export_policy, __path_import_policy};
    use handlers::aphoria::report::__path_push_observations;
    use handlers::aphoria::scan::__path_scan;

    #[derive(OpenApi)]
    #[openapi(
        paths(
            bless,
            export_policy,
            import_policy,
            scan,
            push_observations,
        ),
        components(
            schemas(
                dto::aphoria::BlessRequest,
                dto::aphoria::BlessResponse,
                dto::aphoria::ExportPolicyRequest,
                dto::aphoria::ExportPolicyResponse,
                dto::aphoria::ImportPolicyRequest,
                dto::aphoria::ImportPolicyResponse,
                dto::aphoria::ScanRequest,
                dto::aphoria::ScanResponse,
                dto::aphoria::FindingDto,
                dto::aphoria::ConflictingSourceDto,
                dto::aphoria::PolicySourceDto,
                dto::aphoria::AcknowledgmentDto,
                dto::aphoria::ConflictTraceDto,
                dto::aphoria::ScanSummaryDto,
                dto::aphoria::PushObservationsRequest,
                dto::aphoria::PushObservationsResponse,
                dto::aphoria::ObservationDto,
                dto::aphoria::ObservationValueDto,
                dto::aphoria::ObservationSignatureDto,
            )
        ),
        tags(
            (name = "aphoria", description = "Aphoria code-level truth linting"),
        ),
    )]
    pub(crate) struct AphoriaApiDoc;
}
