import { readFileSync, writeFileSync, existsSync } from 'fs';
import { join } from 'path';
import { logger } from '../utils/logger';

/**
 * Service to auto-update the .env file with Pangolin credentials.
 * Reads the existing .env, updates/adds specific keys, preserves everything else.
 */

const ENV_FILE_PATH = join(__dirname, '../../../.env');

/**
 * Update specific keys in the .env file.
 * - Preserves all existing keys and comments
 * - Updates keys if they already exist (replaces the value)
 * - Appends new keys at the end with a section comment
 * - Does NOT remove any existing keys
 */
export function updateEnvFile(updates: Record<string, string>): { success: boolean; updated: string[]; added: string[]; error?: string } {
  const updated: string[] = [];
  const added: string[] = [];

  try {
    if (!existsSync(ENV_FILE_PATH)) {
      return { success: false, updated: [], added: [], error: `.env file not found at ${ENV_FILE_PATH}` };
    }

    const content = readFileSync(ENV_FILE_PATH, 'utf8');
    const lines = content.split('\n');
    const keysToUpdate = new Set(Object.keys(updates));
    const processedKeys = new Set<string>();

    // Update existing keys in-place
    const updatedLines = lines.map(line => {
      // Skip comments and empty lines
      if (line.startsWith('#') || line.trim() === '') {
        return line;
      }

      // Match KEY=value pattern (handle quoted values too)
      const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)/);
      if (match && match[1] && keysToUpdate.has(match[1])) {
        const key = match[1];
        const oldValue = match[2];
        const newValue = updates[key]!;
        processedKeys.add(key);

        if (oldValue !== newValue) {
          updated.push(key);
          logger.info(`env-writer: updated ${key}`);
          return `${key}=${newValue}`;
        }
        return line; // Value unchanged
      }

      return line;
    });

    // Append any keys that weren't already in the file
    const keysToAdd = [...keysToUpdate].filter(k => !processedKeys.has(k));
    if (keysToAdd.length > 0) {
      // Add a blank line and comment section if we're adding new keys
      updatedLines.push('');
      updatedLines.push('# --- Pangolin Tunnel (auto-configured) ---');
      for (const key of keysToAdd) {
        updatedLines.push(`${key}=${updates[key]}`);
        added.push(key);
        logger.info(`env-writer: added ${key}`);
      }
    }

    // Write back
    writeFileSync(ENV_FILE_PATH, updatedLines.join('\n'), 'utf8');

    logger.info(`env-writer: ${updated.length} updated, ${added.length} added`);
    return { success: true, updated, added };
  } catch (err) {
    const errorMsg = err instanceof Error ? err.message : 'Unknown error';
    logger.error(`env-writer failed: ${errorMsg}`);
    return { success: false, updated: [], added: [], error: errorMsg };
  }
}
