import { createDatabase } from '@pig/db';
import { loadPiggyConfig } from './config';
import { PrimeOpenAIProvider } from './provider';
import { AgentTaskQueue } from './queue';
import { PiggyWorker } from './worker';
import { createPrimeChatProvider, startPiggyChatServer } from './chat-server';

const config = loadPiggyConfig();
const db = createDatabase({ url: config.DATABASE_URL, max: 4 });
const provider = new PrimeOpenAIProvider({
  apiKey: config.PIGGY_INFERENCE_API_KEY,
  baseUrl: config.PIGGY_INFERENCE_BASE,
  model: config.PIGGY_MODEL,
  maxTokens: config.PIGGY_MAX_TOKENS,
});
const chatServer = startPiggyChatServer(db, {
  host: config.PIGGY_CHAT_HOST,
  port: config.PIGGY_CHAT_PORT,
  internalToken: config.PIGGY_INTERNAL_TOKEN,
  allowNonLoopback: config.PIGGY_CHAT_ALLOW_NON_LOOPBACK,
  provider: createPrimeChatProvider({
    apiKey: config.PIGGY_INFERENCE_API_KEY,
    baseUrl: config.PIGGY_INFERENCE_BASE,
    model: config.PIGGY_MODEL,
    maxTokens: config.PIGGY_MAX_TOKENS,
  }),
});
const queue = new AgentTaskQueue(db, config.workerId, config.PIGGY_LEASE_SECONDS);
const worker = new PiggyWorker(db, queue, provider, {
  pollIntervalMs: config.PIGGY_POLL_INTERVAL_MS,
  leaseSeconds: config.PIGGY_LEASE_SECONDS,
});
const shutdown = new AbortController();

process.on('SIGTERM', () => shutdown.abort());
process.on('SIGINT', () => shutdown.abort());

console.log(`[piggy] worker ${config.workerId} using ${provider.model}`);
try {
  await worker.run(shutdown.signal);
} finally {
  chatServer.close();
}
console.log('[piggy] stopped');
