/**
 * Valkey Platform Service Provider
 */

import { BasePlatformServiceProvider } from './base.js';
import * as plugins from '../../../plugins.js';
import type {
  IService,
  IPlatformResource,
  IPlatformServiceConfig,
  IProvisionedResource,
  IEnvVarMapping,
  TPlatformServiceType,
  TPlatformResourceType,
} from '../../../types.js';
import { logger } from '../../../logging.js';
import { getErrorMessage } from '../../../utils/error.js';
import { credentialEncryption } from '../../encryption.js';
import type { Onebox } from '../../onebox.js';

export class ValkeyProvider extends BasePlatformServiceProvider {
  readonly type: TPlatformServiceType = 'valkey';
  readonly displayName = 'Valkey';
  readonly resourceTypes: TPlatformResourceType[] = ['cache'];

  constructor(oneboxRef: Onebox) {
    super(oneboxRef);
  }

  async getDefaultConfig(): Promise<IPlatformServiceConfig> {
    return {
      image: 'valkey/valkey:9.1.0-alpine',
      port: 6379,
      volumes: [`${await this.getPlatformDataDir('valkey')}:/data`],
      environment: {},
    };
  }

  getEnvVarMappings(): IEnvVarMapping[] {
    return [
      { envVar: 'VALKEY_HOST', credentialPath: 'host' },
      { envVar: 'VALKEY_PORT', credentialPath: 'port' },
      { envVar: 'VALKEY_PASSWORD', credentialPath: 'password' },
      { envVar: 'VALKEY_DB', credentialPath: 'db' },
      { envVar: 'VALKEY_URL', credentialPath: 'connectionString' },
    ];
  }

  async deployContainer(): Promise<string> {
    const config = await this.getDefaultConfig();
    const containerName = this.getContainerName();
    const dataDir = await this.getPlatformDataDir('valkey');

    logger.info(`Deploying Valkey platform service as ${containerName}...`);

    // Check if we have existing data and stored credentials
    const platformService = await this.oneboxRef.database.getPlatformServiceByType(this.type);
    let adminCredentials: { username: string; password: string };
    let dataExists = false;

    // Check if data directory has existing Valkey data
    try {
      const stat = await plugins.fs.stat(`${dataDir}/dump.rdb`);
      dataExists = stat.isFile;
      logger.info(`Valkey data directory exists with dump.rdb file`);
    } catch {
      // Also check for appendonly file
      try {
        const stat = await plugins.fs.stat(`${dataDir}/appendonly.aof`);
        dataExists = stat.isFile;
        logger.info(`Valkey data directory exists with appendonly.aof file`);
      } catch {
        dataExists = false;
      }
    }

    if (platformService?.adminCredentialsEncrypted) {
      // Reuse existing credentials from database
      logger.info('Reusing existing Valkey credentials (data directory already initialized)');
      adminCredentials = await credentialEncryption.decrypt<{ username: string; password: string }>(
        platformService.adminCredentialsEncrypted,
      );
    } else {
      // Generate new credentials for fresh deployment
      logger.info('Generating new Valkey admin credentials');
      adminCredentials = {
        username: 'default',
        password: credentialEncryption.generatePassword(32),
      };

      // If data exists but we don't have credentials, we need to wipe the data
      if (dataExists) {
        logger.warn('Valkey data exists but no credentials in database - wiping data directory');
        try {
          await plugins.fs.remove(dataDir, { recursive: true });
        } catch (e) {
          logger.error(`Failed to wipe Valkey data directory: ${getErrorMessage(e)}`);
          throw new Error('Cannot deploy Valkey: data directory exists without credentials');
        }
      }
    }

    // Ensure data directory exists
    try {
      await plugins.fs.mkdir(dataDir, { recursive: true });
    } catch (e) {
      // Directory might already exist
      if (!plugins.isAlreadyExistsError(e)) {
        logger.warn(`Could not create Valkey data directory: ${getErrorMessage(e)}`);
      }
    }

    // Valkey uses command args for password, not env vars
    const containerId = await this.oneboxRef.docker.createPlatformContainer({
      name: containerName,
      image: config.image,
      port: config.port,
      env: [],
      volumes: config.volumes,
      volumeMounts: [await this.getPlatformDataVolume('/data', 'valkey')],
      network: this.getNetworkName(),
      command: ['valkey-server', '--requirepass', adminCredentials.password, '--appendonly', 'yes'],
      removeExistingNames: ['onebox-redis'],
    });

    // Store encrypted admin credentials (only update if new or changed)
    const encryptedCreds = await credentialEncryption.encrypt(adminCredentials);
    if (platformService) {
      await this.oneboxRef.database.updatePlatformService(platformService.id!, {
        containerId,
        adminCredentialsEncrypted: encryptedCreds,
        status: 'starting',
      });
    }

    logger.success(`Valkey container created: ${containerId}`);
    return containerId;
  }

  async stopContainer(containerId: string): Promise<void> {
    logger.info(`Stopping Valkey container ${containerId}...`);
    await this.oneboxRef.docker.stopContainer(containerId);
    logger.success('Valkey container stopped');
  }

  async healthCheck(): Promise<boolean> {
    try {
      logger.info('Valkey health check: starting...');
      const platformService = await this.oneboxRef.database.getPlatformServiceByType(this.type);
      if (!platformService) {
        logger.info('Valkey health check: platform service not found in database');
        return false;
      }
      if (!platformService.adminCredentialsEncrypted) {
        logger.info('Valkey health check: no admin credentials stored');
        return false;
      }
      if (!platformService.containerId) {
        logger.info('Valkey health check: no container ID in database record');
        return false;
      }

      logger.info(`Valkey health check: using container ID ${platformService.containerId.substring(0, 12)}...`);
      const adminCreds = await credentialEncryption.decrypt(platformService.adminCredentialsEncrypted);

      // Use docker exec to run health check inside the container
      const result = await this.oneboxRef.docker.execInContainer(
        platformService.containerId,
        ['valkey-cli', '-a', adminCreds.password, 'ping']
      );

      if (result.exitCode === 0 && result.stdout.includes('PONG')) {
        logger.info('Valkey health check: success');
        return true;
      } else {
        logger.info(`Valkey health check failed: exit code ${result.exitCode}, stdout: ${result.stdout.substring(0, 200)}`);
        return false;
      }
    } catch (error) {
      logger.info(`Valkey health check exception: ${getErrorMessage(error)}`);
      return false;
    }
  }

  async provisionResource(userService: IService): Promise<IProvisionedResource> {
    const platformService = await this.oneboxRef.database.getPlatformServiceByType(this.type);
    if (!platformService || !platformService.adminCredentialsEncrypted) {
      throw new Error('Valkey platform service not found or not configured');
    }

    const adminCreds = await credentialEncryption.decrypt(platformService.adminCredentialsEncrypted);
    const containerName = this.getContainerName();

    // Determine the next available DB index (1-15, reserving 0 for admin)
    const existingResources = await this.oneboxRef.database.getPlatformResourcesByPlatformService(platformService.id!);
    const usedIndexes = new Set<number>();

    for (const resource of existingResources) {
      try {
        const creds = await credentialEncryption.decrypt(resource.credentialsEncrypted);
        if (creds.db) {
          usedIndexes.add(parseInt(creds.db, 10));
        }
      } catch {
        // Skip resources with corrupt credentials
      }
    }

    let dbIndex = -1;
    for (let i = 1; i <= 15; i++) {
      if (!usedIndexes.has(i)) {
        dbIndex = i;
        break;
      }
    }

    if (dbIndex === -1) {
      throw new Error('No available Valkey database indexes (max 15 services per Valkey instance)');
    }

    const resourceName = this.generateResourceName(userService.name);

    logger.info(`Provisioning Valkey database index ${dbIndex} for service '${userService.name}'...`);

    // No server-side creation needed - Valkey DB indexes exist implicitly
    // Just verify connectivity
    if (platformService.containerId) {
      const result = await this.oneboxRef.docker.execInContainer(
        platformService.containerId,
        ['valkey-cli', '-a', adminCreds.password, '-n', String(dbIndex), 'ping']
      );

      if (result.exitCode !== 0 || !result.stdout.includes('PONG')) {
        throw new Error(`Failed to verify Valkey database ${dbIndex}: exit code ${result.exitCode}`);
      }
    }

    logger.success(`Valkey database index ${dbIndex} provisioned for service '${userService.name}'`);

    // Build the credentials and env vars
    const credentials: Record<string, string> = {
      host: containerName,
      port: '6379',
      password: adminCreds.password,
      db: String(dbIndex),
      connectionString: `valkey://:${adminCreds.password}@${containerName}:6379/${dbIndex}`,
    };

    // Map credentials to env vars
    const envVars: Record<string, string> = {};
    for (const mapping of this.getEnvVarMappings()) {
      if (credentials[mapping.credentialPath]) {
        envVars[mapping.envVar] = credentials[mapping.credentialPath];
      }
    }

    return {
      type: 'cache',
      name: resourceName,
      credentials,
      envVars,
    };
  }

  async deprovisionResource(resource: IPlatformResource, credentials: Record<string, string>): Promise<void> {
    const platformService = await this.oneboxRef.database.getPlatformServiceByType(this.type);
    if (!platformService || !platformService.adminCredentialsEncrypted || !platformService.containerId) {
      throw new Error('Valkey platform service not found or not configured');
    }

    const adminCreds = await credentialEncryption.decrypt(platformService.adminCredentialsEncrypted);
    const dbIndex = credentials.db || '0';

    logger.info(`Deprovisioning Valkey database index ${dbIndex} for resource '${resource.resourceName}'...`);

    // Flush the specific database
    const result = await this.oneboxRef.docker.execInContainer(
      platformService.containerId,
      ['valkey-cli', '-a', adminCreds.password, '-n', dbIndex, 'FLUSHDB']
    );

    if (result.exitCode !== 0) {
      logger.warn(`Valkey deprovision returned exit code ${result.exitCode}: ${result.stderr.substring(0, 200)}`);
    }

    logger.success(`Valkey database index ${dbIndex} flushed for resource '${resource.resourceName}'`);
  }
}
