#![allow(
    dead_code,
    unused_imports,
    unused_variables,
    unused_assignments,
    unused,
    clippy::excessive_nesting,
    clippy::vec_init_then_push,
    clippy::ptr_arg,
    clippy::result_large_err
)]

// Provisioning Orchestrator Library
// Exports all modules for use in tests and as a library

use serde::{Deserialize, Serialize};

// Core types that are used throughout the library
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowTask {
    pub id: String,
    pub name: String,
    pub command: String,
    pub args: Vec<String>,
    pub dependencies: Vec<String>,
    pub status: TaskStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub started_at: Option<chrono::DateTime<chrono::Utc>>,
    pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
    pub output: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TaskStatus {
    Pending,
    Running,
    Completed,
    Failed,
    Cancelled,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateServerWorkflow {
    pub infra: String,
    pub settings: String,
    pub servers: Vec<String>,
    pub check_mode: bool,
    pub wait: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskservWorkflow {
    pub infra: String,
    pub settings: String,
    pub taskserv: String,
    pub operation: String, // create, delete, generate, check-updates
    pub check_mode: bool,
    pub wait: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterWorkflow {
    pub infra: String,
    pub settings: String,
    pub cluster_type: String,
    pub operation: String, // create, delete
    pub check_mode: bool,
    pub wait: bool,
}

/// Validate storage type argument
pub fn validate_storage_type(s: &str) -> Result<String, String> {
    let available_types = storage::available_storage_types();
    if available_types.contains(&s.to_string()) {
        Ok(s.to_string())
    } else {
        Err(format!(
            "Invalid storage type '{}'. Available types: {}",
            s,
            available_types.join(", ")
        ))
    }
}

// CLI arguments structure
#[derive(clap::Parser, Clone)]
#[command(author, version, about, long_about = None)]
pub struct Args {
    /// Port to listen on
    #[arg(short, long, default_value = "9090")]
    pub port: u16,

    /// Data directory for storage
    #[arg(short, long, default_value = "./data")]
    pub data_dir: String,

    /// Storage backend type
    #[arg(long, default_value = "filesystem", value_parser = validate_storage_type)]
    pub storage_type: String,

    /// SurrealDB server URL (for surrealdb-server mode)
    #[arg(long)]
    pub surrealdb_url: Option<String>,

    /// SurrealDB namespace
    #[arg(long, default_value = "orchestrator")]
    pub surrealdb_namespace: Option<String>,

    /// SurrealDB database name
    #[arg(long, default_value = "tasks")]
    pub surrealdb_database: Option<String>,

    /// SurrealDB username (for surrealdb-server mode)
    #[arg(long)]
    pub surrealdb_username: Option<String>,

    /// SurrealDB password (for surrealdb-server mode)
    #[arg(long)]
    pub surrealdb_password: Option<String>,

    /// Nushell executable path
    #[arg(long, default_value = "nu")]
    pub nu_path: String,

    /// Provisioning script path
    #[arg(long, default_value = "./core/nulib/provisioning")]
    pub provisioning_path: String,
}

// ============================================================================
// Core Modules (Always Available with 'core' feature)
// ============================================================================

pub mod app_state_builder;
pub mod config;
pub mod config_manager;
pub mod middleware;
pub mod orchestrator_state;
pub mod secrets;
pub mod security;
pub mod security_integration;
pub mod services;
pub mod state;
pub mod storage;

// ============================================================================
// Optional Modules (Feature-Gated)
// ============================================================================

// Audit: Security event logging
#[cfg(feature = "audit")]
pub mod audit;

// Workflow: Orchestration, batch jobs, task management
#[cfg(feature = "workflow")]
pub mod batch;

#[cfg(feature = "workflow")]
pub mod dependency;

#[cfg(feature = "workflow")]
pub mod migration;

#[cfg(feature = "workflow")]
pub mod monitor;

#[cfg(feature = "workflow")]
pub mod queue;

#[cfg(feature = "workflow")]
pub mod rollback;

#[cfg(feature = "workflow")]
pub mod workflow;

// Compliance: Policy evaluation and break-glass emergency access
#[cfg(feature = "compliance")]
pub mod break_glass;

#[cfg(feature = "compliance")]
pub mod compliance;

// Platform: Infrastructure integration
#[cfg(feature = "platform")]
pub mod dns;

#[cfg(feature = "platform")]
pub mod extensions;

#[cfg(feature = "platform")]
pub mod oci;

// SSH: SSH key management
#[cfg(feature = "ssh")]
pub mod ssh;

// Testing: Test environment and container management
#[cfg(feature = "testing")]
pub mod container_manager;

#[cfg(feature = "testing")]
pub mod test_environment;

#[cfg(feature = "testing")]
pub mod test_orchestrator;

// Forward declaration for AppState - actual definition is in main.rs
// This allows modules to reference it via crate::AppState

// ============================================================================
// Re-exports - Stable API
// ============================================================================

// Core types (always available)
pub use app_state_builder::{
    create_orchestrator_app_state, DefaultOrchestratorAppStateBuilder, OrchestratorAppStateBuilder,
};
// Feature-gated re-exports
#[cfg(feature = "audit")]
pub use audit::{
    ActionInfo, ActionType, AuditEvent, AuditLogger, AuditLoggerConfig, AuditStatus, AuditStorage,
    AuthorizationInfo, FileStorage, RetentionPolicy, SiemFormat, UserInfo,
};
#[cfg(feature = "compliance")]
pub use break_glass::{
    create_router as create_break_glass_router, Approval, ApprovalConfig, AutoRevokeConfig,
    BreakGlassAuditEvent, BreakGlassConfig, BreakGlassEventType, BreakGlassRequest,
    BreakGlassService, BreakGlassSession, EmergencyAccessToken, Permission, RequestStatus, Role,
    SessionStatus, User,
};
#[cfg(feature = "compliance")]
pub use compliance::{
    compliance_routes, AccessControlConfig, AccessControlMatrix, ComplianceConfig,
    ComplianceHealthStatus, ComplianceService, ComplianceStatus, ControlResult, CriterionResult,
    DataClassification, DataProtection, DataProtectionConfig, DeletionReport, ErasureReason,
    ExportFormat, GdprService, GdprServiceConfig, IncidentResponse, IncidentResponseConfig,
    IncidentResponseService, IncidentSeverity, IncidentType, Iso27001Compliance, Iso27001Config,
    Iso27001Report, PersonalDataExport, ProtectionReport, RiskAssessment, Soc2Compliance,
    Soc2Config, Soc2Report,
};
#[cfg(feature = "platform")]
pub use dns::{CoreDnsClient, DnsManager, DnsRecord, DnsRecordType};
#[cfg(feature = "platform")]
pub use extensions::{
    Extension, ExtensionLoader, ExtensionManager, ExtensionMetadata, ExtensionType,
};
pub use middleware::AuditMiddleware;
#[cfg(feature = "platform")]
pub use oci::{OciArtifact, OciClient, OciManager, OciManifest};
pub use orchestrator_state::{AppState, SharedState};
pub use secrets::{
    create_secrets_router, Credentials, DynamicSecret, RenewRequest, RevokeRequest, SecretMetadata,
    SecretRequest, SecretStats, SecretType, SecretsConfig, SecretsService,
};
pub use security::{
    auth_middleware,
    token_validator::{
        RevocationStats, TokenClaims, TokenType, TokenValidationError, TokenValidator,
        ValidatedToken,
    },
    AuthError, AuthenticatedUser, SecurityContext,
};
pub use services::{HealthStatus, Service, ServiceManager, ServiceOrchestrator, ServiceStatus};
#[cfg(feature = "ssh")]
pub use ssh::{
    create_ssh_routes, SshConfig, SshKeyDeployment, SshKeyManager, SshKeyRequest, SshKeyStats,
    SshKeyType, SshManagerState, TemporalSshKey,
};
pub use storage::traits::TaskStorage;
#[cfg(feature = "testing")]
pub use test_environment::{TestEnvironment, TestEnvironmentConfig, TestEnvironmentType};
