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;
      }
    }

    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]

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)

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)
  `);
}
