import { z } from 'zod';

const envSchema = z.object({
  TELEGRAM_BOT_TOKEN: z.string().min(1),
  TELEGRAM_ALLOWED_CHAT_IDS: z
    .string()
    .min(1)
    .transform((s) =>
      s
        .split(',')
        .map((id) => id.trim())
        .filter(Boolean)
        .map((id) => {
          const n = Number(id);
          if (isNaN(n)) throw new Error(`Invalid chat ID: ${id}`);
          return n;
        }),
    ),
  TRELLO_API_KEY: z.string().min(1),
  TRELLO_TOKEN: z.string().min(1),
  TRELLO_BOARD_ID: z.string().default('uk7mIrpH'),
  TRELLO_BTW_LIST_ID: z.string().optional(),
  GOOGLE_API_KEY: z.string().min(1),
  HETZI_REPO_PATH: z.string().min(1).default('/home/user/Projects/hetzi'),
  CLAUDE_BIN: z.string().default('claude'),
  CLAUDE_TIMEOUT_MS: z.coerce.number().default(300_000),
  GITHUB_TOKEN: z.string().optional(),
  GITHUB_REPO: z.string().default('alexcodeplace/hetzi'),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
  NODE_ENV: z.string().default('development'),
  CUSTOM_SYSTEM_PROMPT: z.string().optional().default('You are a helpful project assistant.'),
  METRICS_ENDPOINT: z.string().url().optional(),
  BOT_ID: z.string().optional(),
  PROVIDER_CONFIG_ENDPOINT: z.string().url().optional(),
  BOTMASTER_ENDPOINT: z.string().url().optional().default('http://localhost:4321'),
});

export type Env = z.infer<typeof envSchema>;

function loadEnv(): Env {
  const result = envSchema.safeParse(process.env);
  if (!result.success) {
    const missing = result.error.issues
      .map((i) => `  ${i.path.join('.')}: ${i.message}`)
      .join('\n');
    throw new Error(`Missing or invalid environment variables:\n${missing}`);
  }
  return result.data;
}

export const env = loadEnv();
