import { hostname } from 'node:os';
import { z } from 'zod';

const schema = z.object({
  DATABASE_URL: z.string().min(1, 'DATABASE_URL is required.'),
  PIGGY_INFERENCE_API_KEY: z.string().min(1, 'PIGGY_INFERENCE_API_KEY is required.'),
  PIGGY_INFERENCE_BASE: z.string().url().default('https://api.pinference.ai/api/v1'),
  PIGGY_MODEL: z.string().default('nvidia/nemotron-3-nano-30b-a3b'),
  PIGGY_LEASE_SECONDS: z.coerce.number().int().positive().default(300),
  PIGGY_POLL_INTERVAL_MS: z.coerce.number().int().positive().default(2_000),
  PIGGY_MAX_TOKENS: z.coerce.number().int().positive().default(1_024),
  PIGGY_WORKER_ID: z.string().optional(),
  PIGGY_INTERNAL_TOKEN: z.string().min(32, 'PIGGY_INTERNAL_TOKEN must contain at least 32 characters.'),
  PIGGY_CHAT_HOST: z.string().default('127.0.0.1'),
  PIGGY_CHAT_PORT: z.coerce.number().int().positive().default(8_931),
  PIGGY_CHAT_ALLOW_NON_LOOPBACK: z
    .enum(['true', 'false'])
    .default('false')
    .transform((value) => value === 'true'),
});

export type PiggyConfig = z.infer<typeof schema> & { workerId: string };

export function loadPiggyConfig(env: NodeJS.ProcessEnv = process.env): PiggyConfig {
  const parsed = schema.safeParse(env);
  if (!parsed.success) {
    const issues = parsed.error.issues.map((issue) => `  ${issue.path.join('.')}: ${issue.message}`);
    throw new Error(`Invalid Piggy configuration:\n${issues.join('\n')}`);
  }

  return {
    ...parsed.data,
    workerId: parsed.data.PIGGY_WORKER_ID ?? `${hostname()}:${process.pid}`,
  };
}
