#!/usr/bin/env node
/**
 * Yuzu-GCA MCP Server Entry Point
 * 
 * Usage: node dist/main.js
 * Or:    npx tsx src/main.ts
 */

import { bootstrap, type ServerOptions } from "./index.js";
import * as tools from "./tools.js";
import type { DeviceConfig } from "@yuzu-gca/shared";
import * as os from "node:os";
import { randomUUID } from "node:crypto";

// Build device config from environment
const config: DeviceConfig = {
  identity: {
    id: process.env.GCA_DEVICE_ID ?? randomUUID(),
    name: process.env.GCA_DEVICE_NAME ?? os.hostname(),
    platform: os.platform(),
    arch: os.arch(),
    hostname: os.hostname(),
    osVersion: os.release(),
  },
  gateway: {
    url: process.env.GCA_GATEWAY_URL ?? "http://localhost:3000",
    transport: (process.env.GCA_TRANSPORT as any) ?? "sse",
    reconnectDelay: 1000,
    maxReconnectDelay: 30000,
    heartbeatInterval: 15000,
  },
  capabilities: [
    "exec", "process_list",
    "file_list", "file_read", "file_write", "file_move",
    "sysinfo",
  ],
  logLevel: (process.env.GCA_LOG_LEVEL as any) ?? "info",
};

// Build tool handlers map
const toolHandlers = new Map<string, (args: any) => Promise<any>>([
  ["file_list",   tools.file_list],
  ["file_read",   tools.file_read],
  ["file_write",  tools.file_write],
  ["file_move",   tools.file_move],
  ["exec",        tools.exec],
  ["process_list",tools.process_list],
  ["sysinfo",     tools.sysinfo],
]);

const opts: ServerOptions = { config, toolHandlers };
const port = Number(process.env.GCA_PORT ?? 3001);

console.log(`[Yuzu-GCA] Starting MCP Server...`);
console.log(`  Device: ${config.identity.name} (${config.identity.platform}/${config.identity.arch})`);
console.log(`  Gateway: ${config.gateway.url}`);
console.log(`  Tools: ${toolHandlers.size} implemented`);
console.log(`  Port: ${port}`);

bootstrap(opts, port).then(() => {
  console.log(`[Yuzu-GCA] Ready.`);
}).catch(err => {
  console.error(`[Yuzu-GCA] Fatal:`, err);
  process.exit(1);
});
