import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { tmpdir } from 'os';

// Import embedded static files
import { staticFiles } from './embedded-static.js';

// Import server statically
import * as serverModule from './server/index.js';

// Parse args
const args = process.argv.slice(2);
let port = 3000;
for (let i = 0; i < args.length; i++) {
  if (args[i] === '--port' || args[i] === '-p') {
    port = parseInt(args[++i]) || 3000;
  } else if (args[i].startsWith('--port=')) {
    port = parseInt(args[i].split('=')[1]) || 3000;
  } else if (args[i] === '--help' || args[i] === '-h') {
    console.log(`OpenChamber - Web UI for OpenCode
Usage: OpenChamber [options]
Options:
  --port, -p    Port (default: 3000)
  --help, -h    Show help`);
    process.exit(0);
  }
}

// Extract static files to temp directory
const extractDir = join(tmpdir(), 'openchamber-static-' + process.pid);
const distPath = join(extractDir, 'dist');

console.log('Extracting static files...');
mkdirSync(distPath, { recursive: true });

let extractedCount = 0;
for (const [relPath, base64Content] of Object.entries(staticFiles)) {
  const fullPath = join(distPath, relPath);
  const dir = dirname(fullPath);
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true });
  }
  const content = Buffer.from(base64Content, 'base64');
  writeFileSync(fullPath, content);
  extractedCount++;
}
console.log(`Extracted ${extractedCount} files to ${distPath}`);

// Set environment
process.env.OPENCHAMBER_DIST_DIR = distPath;
process.env.OPENCHAMBER_PORT = String(port);

console.log(`Starting OpenChamber on port ${port}...`);

// Start server
if (typeof serverModule.startWebUiServer === 'function') {
  await serverModule.startWebUiServer({ port, attachSignals: true, exitOnShutdown: true });
} else {
  console.error('Error: startWebUiServer not found in server module');
  process.exit(1);
}