/**
 * Configuration management
 */

import path from 'path';
import fs from 'fs';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { Environment, EnvironmentsConfig, DeploymentStatus } from './types';
import { DatabaseManager } from './database';

export class ConfigManager {
  private environmentsFile: string;
  private deploymentLogDir: string;
  private dbFile: string;
  private staticDir: string;

  constructor() {
    const baseDir = path.join(__dirname, '../..');
    this.environmentsFile = path.join(baseDir, 'config/environments.yaml');
    this.deploymentLogDir = path.join(baseDir, 'logs/deployments');
    this.dbFile = path.join(baseDir, 'logs/orchestration.db');
    this.staticDir = path.join(__dirname, '../static');

    // Ensure directories exist
    fs.mkdirSync(this.deploymentLogDir, { recursive: true });
    fs.mkdirSync(this.staticDir, { recursive: true });
    fs.mkdirSync(path.dirname(this.dbFile), { recursive: true });
  }

  getEnvironmentsFile(): string {
    return this.environmentsFile;
  }

  getDeploymentLogDir(): string {
    return this.deploymentLogDir;
  }

  getDbFile(): string {
    return this.dbFile;
  }

  getStaticDir(): string {
    return this.staticDir;
  }

  loadEnvironments(): Environment[] {
    try {
      const content = fs.readFileSync(this.environmentsFile, 'utf-8');
      const config = parseYaml(content) as EnvironmentsConfig;
      return config.environments || [];
    } catch (error) {
      console.error(`Error loading environments: ${error}`);
      return [];
    }
  }

  getEnvironmentByName(name: string): Environment | null {
    const environments = this.loadEnvironments();
    return environments.find(env => env.name === name) || null;
  }

  updateEnvironmentEnabled(environmentName: string, enabled: boolean): void {
    try {
      const content = fs.readFileSync(this.environmentsFile, 'utf-8');
      const config = parseYaml(content) as EnvironmentsConfig;
      
      const env = config.environments.find(e => e.name === environmentName);
      if (env) {
        env.enabled = enabled;
        
        // Write back to file
        const updatedContent = stringifyYaml(config, { indent: 2 });
        fs.writeFileSync(this.environmentsFile, updatedContent, 'utf-8');
      }
    } catch (error) {
      console.error(`Failed to update environment ${environmentName}:`, error);
      throw error;
    }
  }

  getDeploymentStatus(environmentName: string, db: DatabaseManager): DeploymentStatus {
    // Generate realistic mock data
    const statuses = ['deployed', 'deploying', 'healthy', 'degraded'];
    const healthStatuses: ('healthy' | 'degraded' | 'unhealthy' | 'unknown')[] = 
      ['healthy', 'degraded', 'unhealthy', 'unknown'];
    
    const now = new Date();
    const hoursAgo = Math.floor(Math.random() * 48) + 1;
    const lastDeployed = new Date(now.getTime() - hoursAgo * 60 * 60 * 1000);

    const baseStatus: DeploymentStatus = {
      status: statuses[Math.floor(Math.random() * statuses.length)],
      last_deployed: lastDeployed.toISOString(),
      cluster_health: healthStatuses[Math.floor(Math.random() * healthStatuses.length)],
      node_count: Math.floor(Math.random() * 10) + 1,
      pods_running: Math.floor(Math.random() * 45) + 5,
      pods_total: Math.floor(Math.random() * 50) + 10,
      cpu_usage_percent: Math.round((Math.random() * 60 + 20) * 100) / 100,
      memory_usage_percent: Math.round((Math.random() * 55 + 30) * 100) / 100,
      network_in_mbps: Math.round((Math.random() * 990 + 10) * 100) / 100,
      network_out_mbps: Math.round((Math.random() * 490 + 10) * 100) / 100,
      uptime_days: Math.floor(Math.random() * 365) + 1,
      last_health_check: now.toISOString()
    };

    // Get deployment history from database
    baseStatus.total_deployments = db.getDeploymentCount(environmentName);
    const lastDeployment = db.getLastDeployment(environmentName);
    if (lastDeployment) {
      baseStatus.last_deployment = lastDeployment;
    }

    return baseStatus;
  }
}

