// Core deployment types and interfaces
export * from "./types";

// Environment management system
export {
  EnvironmentManager,
  type EnvironmentProvisioningResult,
  type ProvisionedResource,
  type ServiceEndpoint,
  type EnvironmentSnapshot,
  type EnvironmentTemplate,
  type TemplateParameter,
} from "./environment";

// Configuration management system
export {
  EnvironmentConfigManager,
  type ConfigTemplate,
  type EnvironmentPreset,
  type ConfigValidationResult,
  type ConfigExportOptions,
  type ConfigImportResult,
} from "./config";

// CI/CD pipeline management system
export {
  PipelineManager,
  PipelineHooks,
  type PipelineStats,
  type DeploymentMetrics,
  type PipelineManagerOptions,
} from "./pipeline";

// Deployment monitoring system
export {
  DeploymentMonitor,
  type MonitoringDashboard,
  type MonitoringOverview,
  type RealTimeMetrics,
  type AlertSummary,
  type LogSummary,
  type MetricDataPoint,
  type MetricTimeSeries,
  type MonitoringReport,
  type IncidentSummary,
} from "./monitoring";

// Rapid Deployment System - Main orchestrator class
export class RapidDeploymentSystem {
  private environmentManager: EnvironmentManager;
  private configManager: EnvironmentConfigManager;
  private pipelineManager: PipelineManager;
  private monitor: DeploymentMonitor;

  constructor() {
    this.environmentManager = new EnvironmentManager();
    this.configManager = new EnvironmentConfigManager();
    this.pipelineManager = new PipelineManager();
    this.monitor = new DeploymentMonitor();
  }

  // Environment Management
  get environments() {
    return this.environmentManager;
  }

  // Configuration Management
  get configuration() {
    return this.configManager;
  }

  // Pipeline Management
  get pipelines() {
    return this.pipelineManager;
  }

  // Monitoring
  get monitoring() {
    return this.monitor;
  }

  // Quick deployment methods
  async quickDeploy(
    pipelineId: string,
    environment: string,
    options?: {
      skipTests?: boolean;
      skipApproval?: boolean;
      branch?: string;
      tag?: string;
    }
  ) {
    try {
      // Start deployment using pipeline manager
      const deployment = await this.pipelineManager.startDeployment(
        pipelineId,
        {
          environment: environment as any,
          skipTests: options?.skipTests,
          skipApproval: options?.skipApproval,
          branch: options?.branch,
          tag: options?.tag,
        }
      );

      // Start monitoring for the deployment
      await this.monitor.startMonitoring(deployment.id, environment as any, {
        enabled: true,
        provider: "aws_cloudwatch",
        customMetrics: [],
        alerts: [],
        logging: { level: "info", retention: 30, structured: true },
        apm: {
          enabled: true,
          provider: "datadog",
          tracing: true,
          profiling: false,
        },
      });

      return deployment;
    } catch (error) {
      console.error("Quick deployment failed:", error);
      throw error;
    }
  }

  async createEnvironmentFromTemplate(
    templateId: string,
    parameters: Record<string, unknown>,
    options?: {
      autoStart?: boolean;
      monitoring?: boolean;
    }
  ) {
    try {
      // Create environment from template
      const result =
        await this.environmentManager.createEnvironmentFromTemplate(
          templateId,
          parameters
        );

      if (options?.monitoring && result.success) {
        // Start monitoring for the new environment
        await this.monitor.startMonitoring(
          result.environmentId,
          "development", // Default to development for template-based environments
          {
            enabled: true,
            provider: "aws_cloudwatch",
            customMetrics: [],
            alerts: [],
            logging: { level: "info", retention: 30, structured: true },
            apm: {
              enabled: true,
              provider: "datadog",
              tracing: true,
              profiling: false,
            },
          }
        );
      }

      return result;
    } catch (error) {
      console.error("Environment creation from template failed:", error);
      throw error;
    }
  }

  async getDeploymentOverview() {
    const environments = this.environmentManager.getEnvironmentTemplates();
    const pipelines = await this.pipelineManager.getPipelines();

    return {
      environments: environments.length,
      pipelines: pipelines.length,
      activeDeployments: 0, // Would be calculated from actual deployments
      totalDeployments: 0, // Would be calculated from deployment history
      successRate: 95, // Mock value
      averageDeploymentTime: 8, // Mock value in minutes
      systemHealth: "healthy" as const,
    };
  }

  async initializeSystem() {
    try {
      console.log("Initializing Rapid Deployment System...");

      // Initialize default configurations
      await this.configManager.initializeDefaults();

      console.log("Rapid Deployment System initialized successfully");

      return {
        success: true,
        message: "Rapid Deployment System ready for use",
        components: {
          environmentManager: "✓ Ready",
          configManager: "✓ Ready",
          pipelineManager: "✓ Ready",
          monitor: "✓ Ready",
        },
      };
    } catch (error) {
      console.error("Failed to initialize Rapid Deployment System:", error);
      throw error;
    }
  }

  async shutdown() {
    try {
      console.log("Shutting down Rapid Deployment System...");

      // Stop all monitoring
      // In a real implementation, would properly shut down all components

      console.log("Rapid Deployment System shut down successfully");
    } catch (error) {
      console.error("Error during shutdown:", error);
      throw error;
    }
  }
}

// Default instance for easy usage
export const rapidDeployment = new RapidDeploymentSystem();

// Helper utilities for common deployment patterns
export const DeploymentUtils = {
  // Create a full deployment pipeline for a new project
  async createProjectPipeline(projectName: string, repositoryUrl: string) {
    const pipeline = {
      name: `${projectName} CI/CD Pipeline`,
      description: `Automated deployment pipeline for ${projectName}`,
      repository: {
        url: repositoryUrl,
        branch: "main",
      },
      environments: ["development", "staging", "production"],
      stages: [
        { name: "Build", type: "build" as const },
        { name: "Test", type: "test" as const },
        { name: "Security Scan", type: "security_scan" as const },
        { name: "Deploy to Staging", type: "staging_deploy" as const },
        { name: "Integration Tests", type: "integration_test" as const },
        { name: "Approval Gate", type: "approval" as const },
        { name: "Deploy to Production", type: "production_deploy" as const },
        { name: "Post-Deploy Verification", type: "post_deploy_test" as const },
      ],
    };

    return pipeline;
  },

  // Create environment configuration for different tiers
  createEnvironmentConfig(
    type: "development" | "staging" | "production",
    options?: {
      domain?: string;
      region?: string;
      instanceType?: string;
    }
  ) {
    const baseConfig = {
      type,
      region: options?.region || "us-east-1",
      domain: options?.domain || `${type}.example.com`,
      monitoring: { enabled: true },
      ssl: { enabled: type !== "development" },
      autoScale: {
        enabled: type === "production",
        minInstances: type === "production" ? 2 : 1,
        maxInstances: type === "production" ? 10 : 3,
      },
    };

    return baseConfig;
  },

  // Generate deployment summary report
  generateDeploymentSummary(deployments: any[]) {
    const total = deployments.length;
    const successful = deployments.filter((d) => d.status === "success").length;
    const failed = deployments.filter((d) => d.status === "failed").length;
    const pending = deployments.filter(
      (d) => d.status === "pending" || d.status === "in_progress"
    ).length;

    return {
      total,
      successful,
      failed,
      pending,
      successRate: total > 0 ? (successful / total) * 100 : 0,
      failureRate: total > 0 ? (failed / total) * 100 : 0,
    };
  },
};

// Constants and defaults
export const DEPLOYMENT_CONSTANTS = {
  DEFAULT_TIMEOUT: 30 * 60 * 1000, // 30 minutes
  MAX_RETRIES: 3,
  HEALTH_CHECK_INTERVAL: 30 * 1000, // 30 seconds
  MONITORING_INTERVAL: 60 * 1000, // 1 minute
  LOG_RETENTION_DAYS: 30,
  METRIC_RETENTION_HOURS: 24 * 7, // 1 week

  ENVIRONMENT_TYPES: [
    "development",
    "testing",
    "staging",
    "production",
    "preview",
    "hotfix",
  ] as const,

  PIPELINE_STAGES: [
    "build",
    "test",
    "security_scan",
    "quality_gate",
    "staging_deploy",
    "integration_test",
    "approval",
    "production_deploy",
    "post_deploy_test",
    "monitoring",
    "cleanup",
  ] as const,

  DEPLOYMENT_STRATEGIES: [
    "blue_green",
    "rolling",
    "canary",
    "recreate",
    "immediate",
  ] as const,
} as const;

// Version information
export const VERSION = {
  major: 1,
  minor: 0,
  patch: 0,
  build: Date.now(),
  toString() {
    return `${this.major}.${this.minor}.${this.patch}`;
  },
};

console.log(`Rapid Deployment System v${VERSION.toString()} loaded`);
