import "dotenv/config";
import { z } from "zod";

const booleanFromString = z.preprocess((value) => {
  if (typeof value === "boolean") return value;
  if (typeof value !== "string") return value;
  return ["1", "true", "yes"].includes(value.toLowerCase());
}, z.boolean());

const envSchema = z.object({
  SERVER_PORT: z.coerce.number().int().positive().default(4100),
  DATABASE_URL: z.string().url().default("postgres://seo_farm:seo_farm@localhost:5432/seo_farm"),
  S3_ENDPOINT: z.string().url().default("http://localhost:9000"),
  S3_REGION: z.string().default("us-east-1"),
  S3_ACCESS_KEY_ID: z.string().default("seo_farm"),
  S3_SECRET_ACCESS_KEY: z.string().default("seo_farm_secret"),
  S3_BUCKET: z.string().default("seo-farm-artifacts"),
  S3_FORCE_PATH_STYLE: booleanFromString.default(true),
  WORDSTAT_PROVIDER: z.enum(["disabled", "mcp_kv", "yandex_api"]).default("disabled"),
  WORDSTAT_MCP_ENDPOINT: z.string().url().optional(),
  WORDSTAT_API_BASE_URL: z.string().url().optional(),
  WORDSTAT_API_TOKEN: z.string().optional(),
  WORDSTAT_AUTH_TYPE: z.enum(["api_key", "iam_token"]).default("api_key"),
  WORDSTAT_FOLDER_ID: z.string().optional(),
  WORDSTAT_REGION_IDS: z.string().default("225"),
  WORDSTAT_DEVICES: z.string().default("DEVICE_ALL"),
  WORDSTAT_NUM_PHRASES: z.coerce.number().int().positive().default(50),
  SERP_PROVIDER: z.enum(["disabled", "external_api"]).default("disabled"),
  SERP_API_BASE_URL: z.string().url().optional(),
  SERP_API_TOKEN: z.string().optional(),
  PREVIEW_CHROME_PATH: z.string().optional(),
  PREVIEW_SNAPSHOT_CONCURRENCY: z.coerce.number().int().positive().max(4).default(2),
  PREVIEW_SNAPSHOT_WAIT_MS: z.coerce.number().int().nonnegative().max(10_000).default(1400)
});

const parsedEnv = envSchema.parse(process.env);

export const env = {
  serverPort: parsedEnv.SERVER_PORT,
  databaseUrl: parsedEnv.DATABASE_URL,
  s3: {
    endpoint: parsedEnv.S3_ENDPOINT,
    region: parsedEnv.S3_REGION,
    accessKeyId: parsedEnv.S3_ACCESS_KEY_ID,
    secretAccessKey: parsedEnv.S3_SECRET_ACCESS_KEY,
    bucket: parsedEnv.S3_BUCKET,
    forcePathStyle: parsedEnv.S3_FORCE_PATH_STYLE
  },
  marketProviders: {
    wordstat: {
      provider: parsedEnv.WORDSTAT_PROVIDER,
      mcpEndpoint: parsedEnv.WORDSTAT_MCP_ENDPOINT,
      apiBaseUrl: parsedEnv.WORDSTAT_API_BASE_URL,
      apiToken: parsedEnv.WORDSTAT_API_TOKEN,
      authType: parsedEnv.WORDSTAT_AUTH_TYPE,
      folderId: parsedEnv.WORDSTAT_FOLDER_ID,
      regionIds: parsedEnv.WORDSTAT_REGION_IDS.split(",").map((item) => item.trim()).filter(Boolean),
      devices: parsedEnv.WORDSTAT_DEVICES.split(",").map((item) => item.trim()).filter(Boolean),
      numPhrases: parsedEnv.WORDSTAT_NUM_PHRASES,
      hasApiToken: Boolean(parsedEnv.WORDSTAT_API_TOKEN)
    },
    serp: {
      provider: parsedEnv.SERP_PROVIDER,
      apiBaseUrl: parsedEnv.SERP_API_BASE_URL,
      hasApiToken: Boolean(parsedEnv.SERP_API_TOKEN)
    }
  },
  preview: {
    chromePath: parsedEnv.PREVIEW_CHROME_PATH || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    snapshotConcurrency: parsedEnv.PREVIEW_SNAPSHOT_CONCURRENCY,
    snapshotWaitMs: parsedEnv.PREVIEW_SNAPSHOT_WAIT_MS
  }
};
