//! # MockForge Core
//!
//! Core functionality and shared logic for the MockForge mocking framework.
//!
//! This crate provides the foundational building blocks used across all MockForge protocols
//! (HTTP, WebSocket, gRPC, GraphQL). It can be used as a library to programmatically create
//! and manage mock servers, or to build custom mocking solutions.
//!
//! ## Overview
//!
//! MockForge Core includes:
//!
//! - **Routing & Validation**: OpenAPI-based route registration and request validation
//! - **Request/Response Processing**: Template expansion, data generation, and transformation
//! - **Chaos Engineering**: Latency injection, failure simulation, and traffic shaping
//! - **Proxy & Hybrid Mode**: Forward requests to real backends with intelligent fallback
//! - **Request Chaining**: Multi-step request workflows with context passing
//! - **Workspace Management**: Organize and persist mock configurations
//! - **Observability**: Request logging, metrics collection, and tracing
//!
//! ## Quick Start: Embedding MockForge
//!
//! ### Creating a Simple HTTP Mock Server
//!
//! NOTE: marked `ignore` (not `no_run`) — the example references types
//! that moved out of `mockforge-core` during the workspace splits in
//! commits 2ec7625a (openapi) and b75e243c (foundation):
//! `OpenApiSpec`, `OpenApiRouteRegistry`, and `ValidationOptions` now
//! live in `mockforge_openapi`; `LatencyProfile` is in
//! `mockforge_foundation`. Until the example is rewritten using only
//! symbols still re-exported from `mockforge_core`, marking it `ignore`
//! keeps it visible as docs without breaking `cargo test --doc`.
//!
//! ```rust,ignore
//! use mockforge_core::{
//!     Config, LatencyProfile, OpenApiRouteRegistry, OpenApiSpec, Result, ValidationOptions,
//! };
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     // Load OpenAPI specification
//!     let spec = OpenApiSpec::from_file("api.json").await?;
//!
//!     // Create route registry with validation
//!     let registry = OpenApiRouteRegistry::new_with_options(spec, ValidationOptions::default());
//!
//!     // Configure core features
//!     let config = Config {
//!         latency_enabled: true,
//!         failures_enabled: false,
//!         default_latency: LatencyProfile::with_normal_distribution(400, 120.0),
//!         ..Default::default()
//!     };
//!
//!     // Build your HTTP server with the registry
//!     // (See mockforge-http crate for router building)
//!
//!     Ok(())
//! }
//! ```
//!
//! ### Request Chaining
//!
//! Chain multiple requests together with shared context:
//!
//! ```rust,no_run
//! use mockforge_core::{
//!     ChainConfig, ChainDefinition, ChainLink, ChainRequest, RequestChainRegistry, Result,
//! };
//! use mockforge_core::request_chaining::RequestBody;
//! use serde_json::json;
//! use std::collections::HashMap;
//!
//! # async fn example() -> Result<()> {
//! let registry = RequestChainRegistry::new(ChainConfig::default());
//!
//! // Define a chain: create user → add to group → verify membership
//! let chain = ChainDefinition {
//!     id: "user_onboarding".to_string(),
//!     name: "User Onboarding".to_string(),
//!     description: Some("Create user → add to group".to_string()),
//!     config: ChainConfig {
//!         enabled: true,
//!         ..ChainConfig::default()
//!     },
//!     links: vec![
//!         ChainLink {
//!             request: ChainRequest {
//!                 id: "create_user".to_string(),
//!                 method: "POST".to_string(),
//!                 url: "https://api.example.com/users".to_string(),
//!                 headers: HashMap::new(),
//!                 body: Some(RequestBody::json(json!({"name": "{{faker.name}}"}))),
//!                 depends_on: Vec::new(),
//!                 timeout_secs: None,
//!                 expected_status: None,
//!                 scripting: None,
//!             },
//!             extract: HashMap::from([("user_id".to_string(), "create_user.body.id".to_string())]),
//!             store_as: Some("create_user_response".to_string()),
//!         },
//!         ChainLink {
//!             request: ChainRequest {
//!                 id: "add_to_group".to_string(),
//!                 method: "POST".to_string(),
//!                 url: "https://api.example.com/groups/{{user_id}}/members".to_string(),
//!                 headers: HashMap::new(),
//!                 body: None,
//!                 depends_on: vec!["create_user".to_string()],
//!                 timeout_secs: None,
//!                 expected_status: None,
//!                 scripting: None,
//!             },
//!             extract: HashMap::new(),
//!             store_as: None,
//!         },
//!     ],
//!     variables: HashMap::new(),
//!     tags: vec!["onboarding".to_string()],
//! };
//!
//! registry.store().register_chain(chain).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Latency & Failure Injection
//!
//! Simulate realistic network conditions and errors:
//!
//! NOTE: also marked `ignore` for the same reason as the Quick Start
//! example above — `LatencyProfile`, `FailureConfig`, and
//! `create_failure_injector` no longer live in `mockforge_core` after
//! the foundation/openapi extraction. Rewrite to use the actual hosting
//! crates when this section is updated.
//!
//! ```rust,ignore
//! use mockforge_core::{LatencyProfile, FailureConfig, create_failure_injector};
//!
//! // Configure latency simulation
//! let latency = LatencyProfile::with_normal_distribution(400, 120.0)
//!     .with_min_ms(100)
//!     .with_max_ms(800);
//!
//! // Configure failure injection
//! let failure_config = FailureConfig {
//!     global_error_rate: 0.05, // 5% of requests fail
//!     default_status_codes: vec![500, 502, 503],
//!     ..Default::default()
//! };
//!
//! let injector = create_failure_injector(true, Some(failure_config));
//! ```
//!
//! ## Key Modules
//!
//! ### OpenAPI Support
//! - [`openapi`]: Parse and work with OpenAPI specifications
//! - [`openapi_routes`]: Register routes from OpenAPI specs with validation
//! - [`validation`]: Request/response validation against schemas
//!
//! ### Request Processing
//! - [`routing`]: Route matching and registration
//! - [`templating`]: Template variable expansion ({{uuid}}, {{now}}, etc.)
//! - [`request_chaining`]: Multi-step request workflows
//! - [`overrides`]: Dynamic request/response modifications
//!
//! ### Chaos Engineering
//! - [`latency`]: Latency injection with configurable profiles
//! - [`failure_injection`]: Simulate service failures and errors
//! - [`traffic_shaping`]: Bandwidth limiting and packet loss
//!
//! ### Proxy & Hybrid
//! - [`proxy`]: Forward requests to upstream services
//! - [`ws_proxy`]: WebSocket proxy with message transformation
//!
//! ### Persistence & Import
//! - [`workspace`]: Workspace management for organizing mocks
//! - [`workspace_import`]: Import from Postman, Insomnia, cURL, HAR
//! - [`record_replay`]: Record real requests and replay as fixtures
//!
//! ### Observability
//! - [`request_logger`]: Centralized request logging
//! - [`performance`]: Performance metrics and profiling
//!
//! ## Feature Flags
//!
//! This crate supports several optional features:
//!
//! - `openapi`: OpenAPI specification support (enabled by default)
//! - `validation`: Request/response validation (enabled by default)
//! - `templating`: Template expansion (enabled by default)
//! - `chaos`: Chaos engineering features (enabled by default)
//! - `proxy`: Proxy and hybrid mode (enabled by default)
//! - `workspace`: Workspace management (enabled by default)
//!
//! ## Examples
//!
//! See the [examples directory](https://github.com/SaaSy-Solutions/mockforge/tree/main/examples)
//! for complete working examples.
//!
//! ## Related Crates
//!
//! - [`mockforge-http`](https://docs.rs/mockforge-http): HTTP/REST mock server
//! - [`mockforge-grpc`](https://docs.rs/mockforge-grpc): gRPC mock server
//! - [`mockforge-ws`](https://docs.rs/mockforge-ws): WebSocket mock server
//! - [`mockforge-graphql`](https://docs.rs/mockforge-graphql): GraphQL mock server
//! - [`mockforge-plugin-core`](https://docs.rs/mockforge-plugin-core): Plugin development
//! - [`mockforge-data`](https://docs.rs/mockforge-data): Synthetic data generation
//!
//! ## Documentation
//!
//! - [MockForge Book](https://docs.mockforge.dev/)
//! - [API Reference](https://docs.rs/mockforge-core)
//! - [GitHub Repository](https://github.com/SaaSy-Solutions/mockforge)

#![allow(deprecated)]

#[cfg(feature = "advanced")]
pub mod ab_testing;
/// `ai_contract_diff` lives in `mockforge_intelligence::ai_contract_diff`
/// (Issue #562 phase 4). Re-exported here so existing
/// `crate::ai_contract_diff::*` call sites inside core (`ai_studio` /
/// `contract_diff_handler`, `request_capture`) and external
/// `mockforge_core::ai_contract_diff::*` consumers (mockforge-http,
/// mockforge-cli) keep compiling unchanged.
pub use mockforge_intelligence::ai_contract_diff;
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod ai_response;
/// `ai_studio` lives in `mockforge_intelligence::ai_studio` (Issue #562
/// phase 8 — the final AI cluster module). Re-exported here so existing
/// `mockforge_core::ai_studio::*` call sites (mockforge-http handlers,
/// mockforge-ui handlers) keep compiling unchanged. The whole-module move
/// was unblocked by phases 5–7 extracting failure_analysis,
/// contract_validation, reality, and voice (leaves).
pub use mockforge_intelligence::ai_studio;
/// Behavioral cloning of backends - learn from recorded traffic to create realistic mock behavior
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub mod behavioral_cloning;
// Re-export shim for `behavioral_economics`, which moved to
// `mockforge-intelligence` in Issue #562 phase 8. The shim file at
// `src/behavioral_economics.rs` re-exports the new home.
#[cfg(feature = "advanced")]
pub mod behavioral_economics;
#[allow(dead_code)]
pub(crate) mod cache;
pub mod chain_execution;
/// `chaos_utilities` moved to `mockforge_foundation::chaos_utilities`
/// (Issue #562 phase 6) so `mockforge_intelligence::reality` can hold
/// `ChaosConfig` fields without taking a dep on core. Re-exported here
/// for backwards compat.
pub use mockforge_foundation::chaos_utilities;
#[cfg(feature = "advanced")]
#[deprecated(note = "Will be extracted to mockforge-import crate")]
pub mod codegen;
/// Collection export utilities for exporting mock data in various formats
#[allow(dead_code)]
pub(crate) mod collection_export;
pub mod conditions;
pub mod config;
/// Connection pooling for HTTP clients with health checks and idle management
#[allow(dead_code)]
pub(crate) mod connection_pool;
/// `consistency` lives in `mockforge_intelligence::consistency` (Issue
/// #555 phase 7 — moved out of core after its only foreign-to-core deps
/// (`Protocol`, `RealityLevel`) were already available from foundation /
/// intelligence). Re-exported here so existing
/// `mockforge_core::consistency::*` call sites resolve unchanged.
#[cfg(feature = "advanced")]
pub use mockforge_intelligence::consistency;
#[cfg(feature = "contracts")]
#[deprecated(note = "Will be extracted to mockforge-contracts crate")]
/// Consumer-driven contracts for tracking usage and detecting consumer-specific breaking changes
pub mod consumer_contracts;
#[cfg(feature = "contracts")]
/// Contract drift detection. Data types moved to mockforge-foundation
/// (A13–A21); engines (DriftBudgetEngine, ThreatAnalyzer,
/// ProtocolContractRegistry, WebSocket/MQTT/Kafka contract impls) stay
/// here because they depend on OpenApiSpec and jsonschema validators.
pub mod contract_drift;
#[cfg(feature = "contracts")]
/// `contract_validation` lives in `mockforge_intelligence::contract_validation`
/// (Issue #562 phase 5). Re-exported here so existing
/// `mockforge_core::contract_validation::*` call sites
/// (mockforge-cli, in-core ai_studio) keep compiling unchanged.
pub use mockforge_intelligence::contract_validation;
/// Contract webhooks for notifying external systems about contract changes
#[cfg(feature = "contracts")]
#[allow(dead_code)]
pub(crate) mod contract_webhooks;
/// `custom_fixture` was promoted to [`mockforge_openapi::custom_fixture`];
/// re-exported here for backwards compatibility.
pub(crate) use mockforge_openapi::custom_fixture;
/// Data source abstraction for loading test data from multiple sources
pub mod data_source;
/// `deceptive_canary` lives in `mockforge_intelligence::deceptive_canary`
/// (Issue #555 phase 6 — self-contained module moved out of core so
/// the still-in-http `deceptive_canary` middleware + handler can be
/// re-homed once their other deps are detangled). Re-exported here so
/// existing `mockforge_core::deceptive_canary::*` call sites resolve
/// unchanged.
pub use mockforge_intelligence::deceptive_canary;
/// Docker Compose integration for containerized mock deployments
#[allow(dead_code)]
pub(crate) mod docker_compose;
#[cfg(feature = "contracts")]
/// GitOps integration for drift budget violations. Depends on core
/// incidents + contract_drift; stays in core.
pub mod drift_gitops;
// Encryption utility; stays in core (small, widely used).
pub mod encryption;
pub mod error;
/// `failure_injection` was promoted to [`mockforge_foundation::failure_injection`];
/// re-exported here for backwards compatibility.
pub(crate) use mockforge_foundation::failure_injection;
/// `failure_analysis` lives in `mockforge_intelligence::failure_analysis`
/// (Issue #562 phase 5). Re-exported here so existing
/// `mockforge_core::failure_analysis::*` call sites
/// (mockforge-ui handlers, in-core workspace/request + ai_studio/debug_analyzer)
/// keep compiling unchanged.
pub use mockforge_intelligence::failure_analysis;
/// `fidelity` lives in `mockforge_intelligence::fidelity` (Issue #555
/// phase 6 — self-contained module moved out of core so the fidelity
/// HTTP handler could follow). Re-exported here so existing
/// `mockforge_core::fidelity::*` call sites resolve unchanged.
pub use mockforge_intelligence::fidelity;
/// Generic fixture loading utilities shared across protocol crates
pub mod fixture_store;
pub mod generate_config;
#[allow(dead_code)]
pub(crate) mod generative_schema;
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub mod git_watch;
#[cfg(feature = "advanced")]
pub mod graph;
#[cfg(feature = "workspace-mgmt")]
#[deprecated(note = "Will be extracted to mockforge-import crate")]
pub mod import;
#[cfg(feature = "contracts")]
pub mod incidents;
/// `latency` was promoted to [`mockforge_foundation::latency`]; re-exported
/// here so the legacy `mockforge_core::latency::*` path continues to resolve.
pub(crate) use mockforge_foundation::latency;
/// `intelligent_behavior` lives in `mockforge_intelligence::intelligent_behavior`
/// (Issue #562 phase 2). Re-exported here so existing
/// `crate::intelligent_behavior::*` call sites inside core (voice, reality,
/// graph, ai_contract_diff, ai_studio, contract_drift, failure_analysis) and
/// external `mockforge_core::intelligent_behavior::*` consumers keep
/// compiling without churn. Data types had already been promoted to
/// `mockforge-foundation` (A12/A17); this PR moved the LLM-bound engines too.
pub use mockforge_intelligence::intelligent_behavior;
pub mod lifecycle;
#[cfg(feature = "advanced")]
// Config types moved to mockforge-foundation (A14);
// MultiTenantWorkspaceRegistry + WorkspaceRouter stay here (hold Workspace).
pub mod multi_tenant;
pub mod network_profiles;
/// OData function call URI rewrite middleware
pub mod odata_rewrite;
pub mod openapi;
/// Core's concrete [`mockforge_openapi::response_rewriter::ResponseRewriter`]
/// implementation wrapping core's `templating::expand_tokens` +
/// [`overrides::Overrides`]. Used by the OpenAPI router internally; consumer
/// code rarely constructs this directly.
pub mod openapi_rewriter;
/// `openapi_routes` was moved to [`mockforge_openapi::openapi_routes`];
/// re-exported here so every existing
/// `mockforge_core::openapi_routes::{OpenApiRouteRegistry, ValidationOptions,
/// create_registry_from_file, create_registry_from_json, ...}` path
/// keeps resolving.
pub(crate) use mockforge_openapi::openapi_routes;
pub mod output_control;
pub mod overrides;
pub mod performance;
/// `pillar_tracking` and `pillars` were promoted to
/// [`mockforge_foundation::pillar_tracking`] and
/// [`mockforge_foundation::pillars`] (Issue #562 phase 4) so AI modules
/// living in `mockforge-intelligence` can record pillar usage without
/// taking a dep on `mockforge-core`. Re-exported here so existing
/// `mockforge_core::pillar_tracking::*` and `mockforge_core::pillars::*`
/// call sites (10+ files: ui, registry-server, scenarios, http, cli,
/// ai_studio, voice, contract_validation, workspace) keep resolving.
pub use mockforge_foundation::{pillar_tracking, pillars};
/// PR generation lives in `mockforge_intelligence::pr_generation` (Issue #562
/// phase 1); re-exported here so existing `crate::pr_generation::*` call sites
/// and external users that imported `mockforge_core::pr_generation::*` keep
/// compiling without churn.
pub use mockforge_intelligence::pr_generation;
pub mod priority_handler;
pub mod protocol_abstraction;
/// Protocol server lifecycle trait for uniform server startup and shutdown
pub mod protocol_server;
/// Proxy module — migrating to `mockforge-proxy` crate.
/// Import from `mockforge_proxy` instead of `mockforge_core::proxy`.
#[deprecated(note = "Use mockforge_proxy crate directly")]
pub mod proxy;
/// `reality` lives in `mockforge_intelligence::reality` (Issue #562 phase 6).
/// Re-exported here so existing `mockforge_core::reality::*` call sites
/// keep compiling unchanged. The `apply_to_config` inherent method moved
/// to `mockforge_core::reality_apply::apply_reality_to_server_config`
/// (it pokes at concrete `ServerConfig` sub-structs and belongs in core).
pub use mockforge_intelligence::reality;
pub mod reality_apply;
#[cfg(feature = "advanced")]
pub mod reality_continuum;
pub mod record_replay;
pub mod request_capture;
pub mod request_chaining;
/// `request_fingerprint` was promoted to [`mockforge_openapi::request_fingerprint`];
/// re-exported here for backwards compatibility.
pub(crate) use mockforge_openapi::request_fingerprint;
pub mod request_logger;
#[cfg(feature = "scripting")]
pub(crate) mod request_scripting;
// Route chaos has been moved to mockforge-route-chaos crate to avoid Send issues
// Import directly from mockforge-route-chaos crate instead of re-exporting here
// to avoid circular dependency (mockforge-route-chaos depends on mockforge-core for config types)
#[allow(dead_code)]
pub(crate) mod persona_lifecycle_time;
pub mod routing;
/// Runtime validation for SDKs (request/response validation at runtime)
pub mod runtime_validation;
/// `scenario_studio` lives in `mockforge_intelligence::scenario_studio`
/// (Issue #555 phase 7 — self-contained module moved out of core so the
/// scenario_studio HTTP handler could follow). Re-exported here so
/// existing `mockforge_core::scenario_studio::*` call sites resolve
/// unchanged.
#[cfg(feature = "advanced")]
pub use mockforge_intelligence::scenario_studio;
#[cfg(feature = "advanced")]
pub mod scenarios;
pub mod security;
pub mod server_utils;
/// Time travel and snapshot functionality for saving and restoring system states
#[cfg(feature = "advanced")]
pub mod snapshots;
/// Re-export of the extracted [`mockforge_openapi::spec_parser`] module.
pub(crate) use mockforge_openapi::spec_parser;
pub mod stateful_handler;
// sync_watcher stays in core.
pub mod sync_watcher;
/// Template expansion utilities (Send-safe, isolated from templating module)
pub mod template_expansion;
/// Template library system for shared templates, versioning, and marketplace
pub mod template_library;
pub mod templating;
#[cfg(feature = "advanced")]
pub mod time_travel;
#[cfg(feature = "advanced")]
pub mod time_travel_handler;
/// Shared TLS utilities for building rustls server and client configurations.
pub mod tls;
pub mod traffic_shaping;
pub mod validation;
pub mod verification;
/// `voice` was split in Issue #562 phase 7. Six leaf files (command_parser,
/// conversation, hook_transpiler, spec_generator, workspace_scenario_generator,
/// mod) moved to `mockforge_intelligence::voice`. `voice_workspace` (formerly
/// `voice::workspace_builder`) stays here because it depends on multi_tenant,
/// scenarios, workspace, contract_drift, and reality_continuum — all core-only.
/// The `voice` shim consolidates both halves so external callers see one API.
#[cfg(feature = "voice")]
pub mod voice;
#[cfg(feature = "voice")]
pub mod voice_workspace;
#[cfg(feature = "workspace-mgmt")]
// Workspace family (Workspace, WorkspaceConfig, WorkspaceRegistry, etc.) —
// 11k+ LoC surface area. Staying in core; future extraction would need
// its own dedicated planning.
pub mod workspace;
#[cfg(feature = "workspace-mgmt")]
pub mod workspace_import;
#[cfg(feature = "workspace-mgmt")]
pub mod workspace_persistence;
pub mod ws_proxy;

#[cfg(feature = "advanced")]
pub use ab_testing::{
    apply_variant_to_response, select_variant, ABTestConfig, ABTestReport,
    ABTestingMiddlewareState, MockVariant, VariantAllocation, VariantAnalytics, VariantComparison,
    VariantManager, VariantSelectionStrategy,
};
#[cfg(feature = "ai")]
#[deprecated(note = "Will be extracted to mockforge-intelligence crate")]
pub use behavioral_cloning::{
    AmplificationScope, BehavioralSequence, EdgeAmplificationConfig, EdgeAmplifier,
    EndpointProbabilityModel, ErrorPattern, LatencyDistribution, PayloadVariation,
    ProbabilisticModel, SequenceLearner, SequenceStep,
};
pub use chain_execution::{ChainExecutionEngine, ChainExecutionResult, ChainExecutionStatus};
#[deprecated(note = "Use mockforge_chaos::core_chaos_utilities instead")]
pub use chaos_utilities::{ChaosConfig, ChaosEngine, ChaosResult, ChaosStatistics};
pub use conditions::{evaluate_condition, ConditionContext, ConditionError};
pub use config::{
    apply_env_overrides, load_config, load_config_with_fallback, save_config, ApiKeyConfig,
    AuthConfig, ServerConfig,
};
#[cfg(feature = "advanced")]
pub use consistency::{
    ConsistencyEngine, EntityState, ProtocolState, SessionInfo, StateChangeEvent, UnifiedState,
};
pub(crate) use custom_fixture::CustomFixtureLoader;
pub use data_source::{
    DataSource, DataSourceConfig, DataSourceContent, DataSourceFactory, DataSourceManager,
    DataSourceType, GitDataSource, HttpDataSource, LocalDataSource,
};
pub use deceptive_canary::{
    CanaryRoutingStrategy, CanaryStats, DeceptiveCanaryConfig, DeceptiveCanaryRouter,
    TeamIdentifiers,
};
pub use error::{Error, Result};
pub use failure_analysis::{
    ContributingFactor, FailureContext, FailureContextCollector, FailureNarrative,
    FailureNarrativeGenerator, NarrativeFrame,
};
#[deprecated(note = "Use mockforge_chaos::core_failure_injection instead")]
pub(crate) use failure_injection::FailureInjector;
pub use fidelity::{FidelityCalculator, FidelityScore, SampleComparator, SchemaComparator};
pub use generate_config::{
    discover_config_file, load_generate_config, load_generate_config_with_fallback,
    save_generate_config, BarrelType, GenerateConfig, GenerateOptions, InputConfig, OutputConfig,
    PluginConfig,
};
#[deprecated(note = "Will be extracted to mockforge-workspace crate")]
pub use git_watch::{GitWatchConfig, GitWatchService};
#[cfg(feature = "advanced")]
pub use graph::{
    builder::GraphBuilder, relationships, ClusterType, EdgeType, GraphCluster, GraphData,
    GraphEdge, GraphNode, NodeType, Protocol as GraphProtocol,
};
pub(crate) use latency::LatencyProfile;
pub use lifecycle::{
    LifecycleHook, LifecycleHookRegistry, MockLifecycleEvent, RequestContext, ResponseContext,
    ServerLifecycleEvent,
};
#[cfg(feature = "advanced")]
pub use multi_tenant::{
    MultiTenantConfig, MultiTenantWorkspaceRegistry, RoutingStrategy, TenantWorkspace,
    WorkspaceContext, WorkspaceRouter, WorkspaceStats,
};
#[deprecated(note = "Use mockforge_chaos::core_network_profiles instead")]
pub use network_profiles::{NetworkProfile, NetworkProfileCatalog};
pub(crate) use openapi::OpenApiSpec;
pub use output_control::{
    apply_banner, apply_extension, apply_file_naming_template, build_file_naming_context,
    process_generated_file, BarrelGenerator, FileNamingContext, GeneratedFile,
};
pub use overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
pub use pillars::{Pillar, PillarMetadata};
pub use priority_handler::{
    CustomFixtureStep, FailureInjectionStep, GenerationResult, MockGenerator, MockResponse,
    PriorityHttpHandler, PriorityRequest, PriorityResponse, PriorityStep, SimpleMockGenerator,
};
pub use protocol_abstraction::{
    MessagePattern, MiddlewareAction, MiddlewareChain, Protocol, ProtocolMiddleware,
    ProtocolRequest, ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation, SpecRegistry,
    ValidationError as ProtocolValidationError, ValidationResult as ProtocolValidationResult,
};
#[deprecated(note = "Will be extracted to mockforge-proxy crate")]
pub use proxy::{ProxyConfig, ProxyHandler, ProxyResponse};
pub use reality::{PresetMetadata, RealityConfig, RealityEngine, RealityLevel, RealityPreset};
#[cfg(feature = "advanced")]
pub use reality_continuum::{
    ContinuumConfig, ContinuumRule, MergeStrategy, RealityContinuumEngine, ResponseBlender,
    TimeSchedule, TransitionCurve, TransitionMode,
};
pub use record_replay::{
    clean_old_fixtures, list_fixtures, list_ready_fixtures, list_smoke_endpoints, RecordHandler,
    RecordReplayHandler, RecordedRequest, ReplayHandler,
};
pub use request_chaining::{
    ChainConfig, ChainContext, ChainDefinition, ChainExecutionContext, ChainLink, ChainRequest,
    ChainResponse, ChainStore, ChainTemplatingContext, RequestChainRegistry,
};
pub(crate) use request_fingerprint::{RequestFingerprint, ResponsePriority, ResponseSource};
pub use request_logger::{
    create_grpc_log_entry, create_http_log_entry, create_http_log_entry_with_query,
    create_websocket_log_entry, get_global_logger, init_global_logger, log_request_global,
    CentralizedRequestLogger, RequestLogEntry,
};
// Route chaos types moved to mockforge-route-chaos crate
// Import directly: use mockforge_route_chaos::{RouteChaosInjector, RouteFaultResponse, RouteMatcher};
pub use routing::{HttpMethod, Route, RouteRegistry};
pub use runtime_validation::{
    RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
};
#[cfg(feature = "advanced")]
pub use scenario_studio::{
    ConditionOperator, FlowCondition, FlowConnection, FlowDefinition, FlowExecutionResult,
    FlowExecutor, FlowPosition, FlowStep, FlowStepResult, FlowType, FlowVariant, StepType,
};
#[cfg(feature = "advanced")]
pub use scenarios::types::StepResult;
#[cfg(feature = "advanced")]
pub use scenarios::{
    ScenarioDefinition, ScenarioExecutor, ScenarioParameter, ScenarioRegistry, ScenarioResult,
    ScenarioStep,
};
pub use server_utils::errors::{json_error, json_success};
pub use server_utils::{create_socket_addr, localhost_socket_addr, wildcard_socket_addr};
#[cfg(feature = "advanced")]
pub use snapshots::{SnapshotComponents, SnapshotManager, SnapshotManifest, SnapshotMetadata};
pub use stateful_handler::{
    ResourceIdExtract, StateInfo, StateResponse, StatefulConfig, StatefulResponse,
    StatefulResponseHandler, TransitionTrigger,
};
#[cfg(feature = "workspace-mgmt")]
pub use sync_watcher::{FileChange, SyncEvent, SyncService, SyncWatcher};
pub use template_library::{
    TemplateLibrary, TemplateLibraryEntry, TemplateLibraryManager, TemplateMarketplace,
    TemplateMetadata, TemplateVersion,
};
pub use templating::{expand_str, expand_tokens};
#[cfg(feature = "advanced")]
pub use time_travel::{
    cron::{CronJob, CronJobAction, CronScheduler},
    get_global_clock, is_time_travel_enabled, now as time_travel_now, register_global_clock,
    unregister_global_clock, RepeatConfig, ResponseScheduler, ScheduledResponse, TimeScenario,
    TimeTravelConfig, TimeTravelManager, TimeTravelStatus, VirtualClock,
};
#[cfg(feature = "advanced")]
pub use time_travel_handler::{
    time_travel_middleware, ScheduledResponseWrapper, TimeTravelHandler,
};
#[deprecated(note = "Use mockforge_chaos::core_traffic_shaping instead")]
pub use traffic_shaping::{BandwidthConfig, BurstLossConfig, TrafficShaper, TrafficShapingConfig};
pub use uuid::Uuid;
pub use validation::{validate_openapi_operation_security, validate_openapi_security, Validator};
pub use verification::{
    matches_verification_pattern, verify_at_least, verify_never, verify_requests, verify_sequence,
    VerificationCount, VerificationRequest, VerificationResult,
};
#[cfg(feature = "voice")]
pub use voice::{
    ConversationContext, ConversationManager, ConversationState, GeneratedWorkspaceScenario,
    HookTranspiler, ParsedCommand, ParsedWorkspaceScenario, VoiceCommandParser, VoiceSpecGenerator,
    WorkspaceConfigSummary, WorkspaceScenarioGenerator,
};
#[cfg(feature = "workspace-mgmt")]
pub use workspace::promotion_trait::PromotionService;
#[cfg(feature = "workspace-mgmt")]
pub use workspace::{EntityId, Folder, MockRequest, Workspace, WorkspaceConfig, WorkspaceRegistry};
#[cfg(feature = "workspace-mgmt")]
pub use workspace_import::{
    create_workspace_from_curl, create_workspace_from_har, create_workspace_from_insomnia,
    create_workspace_from_postman, import_postman_to_existing_workspace,
    import_postman_to_workspace, WorkspaceImportConfig, WorkspaceImportResult,
};
#[cfg(feature = "workspace-mgmt")]
pub use workspace_persistence::WorkspacePersistence;
pub use ws_proxy::{WsProxyConfig, WsProxyHandler, WsProxyRule};
// Note: ValidationError and ValidationResult from spec_parser conflict with schema_diff::ValidationError
// Use qualified paths: spec_parser::ValidationError, spec_parser::ValidationResult

// ── Organized module facades (R10) ───────────────────────────────────────────
// These provide a namespaced access path for new code. Existing flat re-exports
// above remain for backward compatibility. Prefer these for new imports.

/// Routing, route matching, and OpenAPI route generation
pub mod routes {
    pub use crate::openapi::{
        OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSpec,
    };
    pub use crate::openapi_routes::{
        create_registry_from_file, create_registry_from_json, OpenApiRouteRegistry,
        ValidationOptions,
    };
    pub use crate::routing::{HttpMethod, Route, RouteRegistry};
}

/// Middleware, protocol abstractions, and request processing
pub mod middleware {
    pub use crate::latency::LatencyInjector;
    pub use crate::overrides::{OverrideMode, OverrideRule, Overrides, PatchOp};
    pub use crate::protocol_abstraction::{
        MessagePattern, MiddlewareAction, MiddlewareChain, Protocol, ProtocolMiddleware,
        ProtocolRequest, ProtocolResponse, RequestMatcher, ResponseStatus, SpecOperation,
        SpecRegistry,
    };
}

/// Mock response generation and priority handling
pub mod generation {
    pub use crate::priority_handler::{
        CustomFixtureStep, FailureInjectionStep, GenerationResult, MockGenerator, MockResponse,
        PriorityHttpHandler, PriorityRequest, PriorityResponse, PriorityStep, SimpleMockGenerator,
    };
    pub use crate::stateful_handler::{StatefulConfig, StatefulResponse, StatefulResponseHandler};
}

/// Request/response validation
pub mod validate {
    pub use crate::runtime_validation::{
        RuntimeValidationError, RuntimeValidationResult, RuntimeValidatorConfig, SchemaMetadata,
    };
    pub use crate::spec_parser::{GraphQLValidator, OpenApiValidator, SpecFormat};
    pub use crate::validation::{
        validate_openapi_operation_security, validate_openapi_security, Validator,
    };
    pub use crate::verification::{
        matches_verification_pattern, verify_at_least, verify_never, verify_requests,
        verify_sequence, VerificationCount, VerificationRequest, VerificationResult,
    };
}

/// Fixture loading utilities
pub mod fixtures {
    pub use crate::custom_fixture::{CustomFixture, CustomFixtureLoader, NestedFixture};
    pub use crate::fixture_store::{
        load_fixtures_from_dir, FixtureFileFormat, FixtureFileGranularity, FixtureLoadErrorMode,
        FixtureLoadOptions,
    };
    pub use crate::record_replay::{
        RecordHandler, RecordReplayHandler, RecordedRequest, ReplayHandler,
    };
}

/// Core configuration for MockForge
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default)]
pub struct Config {
    /// Enable latency simulation
    pub latency_enabled: bool,
    /// Enable failure simulation
    pub failures_enabled: bool,
    /// Enable response overrides
    pub overrides_enabled: bool,
    /// Enable traffic shaping (bandwidth + burst loss)
    pub traffic_shaping_enabled: bool,
    /// Failure injection configuration
    pub failure_config: Option<failure_injection::FailureConfig>,
    /// Proxy configuration
    pub proxy: Option<ProxyConfig>,
    /// Default latency profile
    pub default_latency: LatencyProfile,
    /// Traffic shaping configuration
    pub traffic_shaping: TrafficShapingConfig,
    /// Random chaos configuration
    pub chaos_random: Option<ChaosConfig>,
    /// Maximum number of request logs to keep in memory (default: 1000)
    /// Helps prevent unbounded memory growth from request logging
    pub max_request_logs: usize,
    /// Time travel configuration for temporal testing
    pub time_travel: TimeTravelConfig,
}

/// Default configuration
impl Default for Config {
    fn default() -> Self {
        Self {
            latency_enabled: true,
            failures_enabled: false,
            overrides_enabled: true,
            traffic_shaping_enabled: false,
            failure_config: None,
            proxy: None,
            default_latency: LatencyProfile::default(),
            traffic_shaping: TrafficShapingConfig::default(),
            chaos_random: None,
            max_request_logs: 1000, // Default: keep last 1000 requests
            time_travel: TimeTravelConfig::default(),
        }
    }
}

impl Config {
    /// Create a ChaosEngine from the chaos_random configuration if enabled
    pub fn create_chaos_engine(&self) -> Option<ChaosEngine> {
        self.chaos_random.as_ref().map(|config| ChaosEngine::new(config.clone()))
    }

    /// Check if random chaos mode is enabled
    pub fn is_chaos_random_enabled(&self) -> bool {
        self.chaos_random.as_ref().map(|c| c.enabled).unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert!(config.latency_enabled);
        assert!(!config.failures_enabled);
        assert!(config.overrides_enabled);
        assert!(!config.traffic_shaping_enabled);
        assert!(config.failure_config.is_none());
        assert!(config.proxy.is_none());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config::default();
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("latency_enabled"));
        assert!(json.contains("failures_enabled"));
    }

    #[test]
    fn test_config_deserialization() {
        // Use default config and modify
        let config = Config {
            latency_enabled: false,
            failures_enabled: true,
            ..Default::default()
        };

        // Serialize and deserialize
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: Config = serde_json::from_str(&json).unwrap();

        assert!(!deserialized.latency_enabled);
        assert!(deserialized.failures_enabled);
        assert!(deserialized.overrides_enabled);
    }

    #[test]
    fn test_config_with_custom_values() {
        let config = Config {
            latency_enabled: false,
            failures_enabled: true,
            ..Default::default()
        };

        assert!(!config.latency_enabled);
        assert!(config.failures_enabled);
    }
}
