const path = require('path');

/**
 * CLI output helper untuk default ringkas dan verbose mode.
 *
 * Default behavior: mute() di awal command, capture warning, render
 * structured summary di akhir via printCreateSummary().
 * Verbose mode: skip mute(), output original tetap muncul apa adanya.
 */
class CliOutput {
  constructor() {
    this._muted = false;
    this._origLog = null;
    this._origWarn = null;
    this._capturedWarnings = [];
  }

  mute() {
    if (this._muted) return;
    this._origLog = console.log;
    this._origWarn = console.warn;
    console.log = () => {};
    console.warn = (...args) => {
      this._capturedWarnings.push(args.map(String).join(' '));
    };
    this._muted = true;
  }

  unmute() {
    if (!this._muted) return;
    console.log = this._origLog;
    console.warn = this._origWarn;
    this._muted = false;
  }

  drainWarnings() {
    const seen = new Set();
    const out = [];
    for (const raw of this._capturedWarnings) {
      const clean = raw.replace(/^Warning:\s*/i, '').trim();
      if (!seen.has(clean)) {
        seen.add(clean);
        out.push(clean);
      }
    }
    this._capturedWarnings = [];
    return out;
  }

  formatSize(bytes) {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
  }

  toRelative(absPath, cwd) {
    return path.relative(cwd || process.cwd(), absPath).replace(/\\/g, '/');
  }

  printCreateSummary(data) {
    const out = (line) => process.stdout.write(line + '\n');

    out('Configuration:');
    out(`  Project      ${data.config.project}`);
    if (data.config.endpoint) out(`  Endpoint     ${data.config.endpoint}`);
    const dbLine = data.config.force
      ? `${data.config.database} (force overwrite)`
      : data.config.database;
    out(`  Database     ${dbLine}`);
    if (data.config.config) {
      out(`  Config       ${data.config.config}`);
    }
    out('');

    if (data.payload) {
      out('Payload:');
      out(`  Source       ${data.payload.source}`);
      out(`  Status       ${data.payload.status}`);
      for (const w of data.payload.warnings || []) {
        out(`  ! Warning    ${w}`);
      }
      out('');
    }

    if (data.schemaValidation) {
      out('Schema Validation:');
      if (data.schemaValidation.status === 'ok') {
        const n = data.schemaValidation.columnsChecked || 0;
        out(`  Status       OK (${n} column${n === 1 ? '' : 's'} match database)`);
      } else if (data.schemaValidation.status === 'skipped') {
        out('  Status       SKIPPED (--skip-schema-check)');
        if (data.schemaValidation.reason) {
          out(`  Reason       ${data.schemaValidation.reason}`);
        }
      }
      out('');
    }

    if (data.archive && data.archive.count > 0) {
      out('Archive (force):');
      out(`  Generation ${data.archive.generation} - ${data.archive.count} file(s) archived`);
      out('');
    }

    if (data.generated && data.generated.length > 0) {
      out('Generated:');
      const maxLen = Math.max(...data.generated.map(g => g.path.length));
      const padding = Math.max(maxLen + 2, 50);
      for (const g of data.generated) {
        out(`  ${g.path.padEnd(padding)} ${g.size}`);
      }
      out('');
    }

    if (data.examples) {
      out(`Example files: ${data.examples.folder} (${data.examples.formats.join(', ')})`);
      out('');
    }

    out(`OK Operation completed in ${data.duration}s`);
  }

  printDashboardSummary(data) {
    const out = (line) => process.stdout.write(line + '\n');

    out('Configuration:');
    out(`  Project      ${data.config.project}`);
    out(`  Dashboard    ${data.config.dashboard}`);
    const dbLine = data.config.force
      ? `${data.config.database} (force overwrite)`
      : data.config.database;
    out(`  Database     ${dbLine}`);
    out('');

    if (data.payload) {
      out('Payload:');
      out(`  Source       ${data.payload.source}`);
      out(`  Status       ${data.payload.status}`);
      for (const w of data.payload.warnings || []) {
        out(`  ! Warning    ${w}`);
      }
      out('');
    }

    if (data.archive) {
      out('Archive:');
      out(`  ${data.archive.path}`);
      out('');
    }

    if (data.generated && data.generated.length > 0) {
      out('Generated:');
      const maxLen = Math.max(...data.generated.map(g => g.path.length));
      const padding = Math.max(maxLen + 2, 50);
      for (const g of data.generated) {
        out(`  ${g.path.padEnd(padding)} ${g.size}`);
      }
      out('');
    }

    if (data.endpoint) {
      out(`Endpoint: ${data.endpoint}`);
      out('');
    }

    out(`OK Operation completed in ${data.duration}s`);
  }

  printDashboardValidateOnlySummary(data) {
    const out = (line) => process.stdout.write(line + '\n');

    out('Configuration:');
    out(`  Project      ${data.config.project}`);
    out(`  Dashboard    ${data.config.dashboard}`);
    out(`  Database     ${data.config.database}`);
    out('');

    if (data.payload) {
      out('Payload:');
      out(`  Source       ${data.payload.source}`);
      out(`  Status       ${data.payload.status}`);
      for (const w of data.payload.warnings || []) {
        out(`  ! Warning    ${w}`);
      }
      out('');
    }

    out(`OK Validation passed in ${data.duration}s`);
  }
}

module.exports = new CliOutput();
