import { ObjectStorageContainer } from './classes/objectstoragecontainer.ts';
import type { IObjectStorageConfig } from './types.ts';

export async function runCli(): Promise<void> {
  const args = Deno.args;
  const command = args[0];

  if (!command || command === 'help') {
    printHelp();
    return;
  }

  if (command === 'server') {
    const configOverrides: Partial<IObjectStorageConfig> = {};

    // Parse CLI args
    for (let i = 1; i < args.length; i++) {
      switch (args[i]) {
        case '--storage-port':
          configOverrides.objstPort = parseInt(args[++i], 10);
          break;
        case '--ui-port':
          configOverrides.uiPort = parseInt(args[++i], 10);
          break;
        case '--storage-dir':
          configOverrides.storageDirectory = args[++i];
          break;
        case '--ephemeral':
          // Use a temp directory for storage
          configOverrides.storageDirectory = './.nogit/objstdata';
          break;
        case '--cluster-enabled':
          configOverrides.clusterEnabled = true;
          break;
        case '--cluster-node-id':
          configOverrides.clusterNodeId = args[++i];
          break;
        case '--cluster-quic-port':
          configOverrides.clusterQuicPort = parseInt(args[++i], 10);
          break;
        case '--cluster-seed-nodes':
          configOverrides.clusterSeedNodes = args[++i].split(',').map(s => s.trim()).filter(Boolean);
          break;
        case '--drive-paths':
          configOverrides.drivePaths = args[++i].split(',').map(s => s.trim()).filter(Boolean);
          break;
        case '--erasure-data-shards':
          configOverrides.erasureDataShards = parseInt(args[++i], 10);
          break;
        case '--erasure-parity-shards':
          configOverrides.erasureParityShards = parseInt(args[++i], 10);
          break;
      }
    }

    const container = new ObjectStorageContainer(configOverrides);

    // Graceful shutdown
    const shutdown = async () => {
      console.log('\nShutting down...');
      await container.stop();
      Deno.exit(0);
    };

    Deno.addSignalListener('SIGINT', shutdown);
    Deno.addSignalListener('SIGTERM', shutdown);

    await container.start();
  } else {
    console.error(`Unknown command: ${command}`);
    printHelp();
    Deno.exit(1);
  }
}

function printHelp(): void {
  console.log(`
ObjectStorage - S3-compatible object storage server with management UI

Usage:
  objectstorage server [options]

Server Options:
  --ephemeral              Use local .nogit/objstdata for storage
  --storage-port PORT      Storage API port (default: 9000, env: OBJST_PORT)
  --ui-port PORT           Management UI port (default: 3000, env: UI_PORT)
  --storage-dir DIR        Storage directory (default: /data, env: OBJST_STORAGE_DIR)

Clustering Options:
  --cluster-enabled        Enable cluster mode (env: OBJST_CLUSTER_ENABLED)
  --cluster-node-id ID     Unique node identifier (env: OBJST_CLUSTER_NODE_ID)
  --cluster-quic-port PORT QUIC transport port (default: 4433, env: OBJST_CLUSTER_QUIC_PORT)
  --cluster-seed-nodes LIST Comma-separated seed node addresses (env: OBJST_CLUSTER_SEED_NODES)
  --drive-paths LIST       Comma-separated drive mount paths (env: OBJST_DRIVE_PATHS)
  --erasure-data-shards N  Erasure coding data shards (default: 4, env: OBJST_ERASURE_DATA_SHARDS)
  --erasure-parity-shards N Erasure coding parity shards (default: 2, env: OBJST_ERASURE_PARITY_SHARDS)

Environment Variables:
  OBJST_PORT               Storage API port
  UI_PORT                  Management UI port
  OBJST_STORAGE_DIR        Storage directory
  OBJST_ACCESS_KEY         Access key (default: admin)
  OBJST_SECRET_KEY         Secret key (default: admin)
  OBJST_ADMIN_PASSWORD     Admin UI password (default: admin)
  OBJST_REGION             Storage region (default: us-east-1)
  OBJST_CLUSTER_ENABLED    Enable clustering (true/false)
  OBJST_CLUSTER_NODE_ID    Unique node identifier
  OBJST_CLUSTER_QUIC_PORT  QUIC transport port (default: 4433)
  OBJST_CLUSTER_SEED_NODES Comma-separated seed node addresses
  OBJST_DRIVE_PATHS        Comma-separated drive mount paths
  OBJST_ERASURE_DATA_SHARDS  Erasure data shards (default: 4)
  OBJST_ERASURE_PARITY_SHARDS Erasure parity shards (default: 2)
  OBJST_ERASURE_CHUNK_SIZE Erasure chunk size in bytes (default: 4194304)
  OBJST_HEARTBEAT_INTERVAL_MS Cluster heartbeat interval (default: 5000)
  OBJST_HEARTBEAT_TIMEOUT_MS  Cluster heartbeat timeout (default: 30000)
  OBJST_ALLOW_INSECURE_DEFAULTS Allow admin/admin defaults on /data for disposable development
  `);
}
