import z from "zod";
import { readFileSync } from "node:fs";
import { parse as yamlParse } from "yaml";
import { EOL } from "node:os";

const schema = z.object({
  command: z.object({
    interval: z.number().int().positive(),
    maxParallels: z.number().int().positive(),
  }),
  earthquake: z.object({
    requireMaxScale: z.union([
      z.literal(10),
      z.literal(20),
      z.literal(30),
      z.literal(40),
      z.literal(45),
      z.literal(50),
      z.literal(55),
      z.literal(60),
      z.literal(70),
    ]),
    useHistoryData: z.boolean(),
    reconnectInterval: z.number().positive(),
  }),
  uwuzu: z.object({
    token: z.string().length(64),
    origin: z.string().refine(data => {
      try {
        return new URL(data).origin === data;
      } catch {
        return false;
      }
    }),
  }),
  ueuse: z.object({
    maxRetries: z.number().int().positive(),
    retryInterval: z.number().positive(),
    maxLengthWithPublic: z.number().int().nonnegative(),
  }),
  debug: z.boolean().optional(),
});

const configFile = readFileSync(`${import.meta.dirname}/../../config/config.yaml`, "utf-8");
const configObj = yamlParse(configFile);
const result = schema.safeParse(configObj);

if (!result.success) {
  console.error("Config: configが無効です。");
  console.error(`  ${result.error.issues.map(issue => issue.message).join(EOL).replaceAll(EOL, `${EOL}  `)}`);
  process.exit(1);
}

const config = result.data;
export default config;