import { isNumber, isPlainObject, isString } from "es-toolkit";
import { dirname, resolve } from "node:path";

import type { ConfigValidationIssue } from "./schema/issues";
import type { DefaultsConfig, EngineRuntimeConfig, RawTargetConfig, ResolvedTargetBase } from "./types";

import { checkerRegistry } from "./runner";
import { issue, throwConfigIssues } from "./schema/issues";
import { asValidatedConfig, type RawProbeConfig } from "./schema/types";
import { validateProbeConfigContract } from "./schema/validate";
import { parseDuration } from "./utils";
import { resolveVariables } from "./variables";

const DEFAULT_HOST = "127.0.0.1";
const DEFAULT_PORT = 3000;
const DEFAULT_DATA_DIR = "./data";
const DEFAULT_INTERVAL = "30s";
const DEFAULT_TIMEOUT = "10s";
const DEFAULT_MAX_CONCURRENT_CHECKS = 20;
const DEFAULT_RETENTION = "7d";

export interface ResolvedConfig {
  configDir: string;
  dataDir: string;
  host: string;
  maxConcurrentChecks: number;
  port: number;
  retentionMs: number;
  targets: ResolvedTargetBase[];
}

export async function loadConfig(configPath: string): Promise<ResolvedConfig> {
  const file = Bun.file(configPath);

  if (!(await file.exists())) {
    throw new Error(`配置文件不存在: ${configPath}`);
  }

  const content = await file.text();
  const parsed = Bun.YAML.parse(content);

  if (!parsed) {
    throw new Error("配置文件内容为空或格式无效");
  }

  const variableResult = resolveVariables(parsed);
  if (variableResult.issues.length > 0) {
    throwConfigIssues(dedupeIssues(variableResult.issues));
  }

  const resolvedVariablesConfig = variableResult.config;
  const contractResult = validateProbeConfigContract(resolvedVariablesConfig, checkerRegistry);
  if (contractResult.config === null && !canRunSemanticValidation(resolvedVariablesConfig)) {
    throwConfigIssues(contractResult.issues);
  }
  const semanticInput = (contractResult.config ?? resolvedVariablesConfig) as RawProbeConfig;
  const validationIssues = validateConfig(semanticInput);

  const allIssues = [...contractResult.issues, ...validationIssues];
  if (contractResult.config === null) {
    if (allIssues.length > 0) {
      throwConfigIssues(dedupeIssues(allIssues));
    }
    throw new Error("配置文件内容为空或格式无效");
  }

  const raw = contractResult.config;

  const validated = asValidatedConfig(raw);

  const configDir = dirname(resolve(configPath));
  const server = validated.server ?? {};
  const runtime = validated.runtime ?? {};
  const defaults = validated.defaults ?? {};

  const host = server.host ?? DEFAULT_HOST;
  const port = server.port ?? DEFAULT_PORT;
  const dataDir = resolve(configDir, server.dataDir ?? DEFAULT_DATA_DIR);

  const maxConcurrentChecks = resolveMaxConcurrentChecks(runtime);
  const retentionMs = resolveRetention(runtime);

  const allRuntimeIssues = [...allIssues];
  if (allRuntimeIssues.length > 0) {
    throwConfigIssues(dedupeIssues(allRuntimeIssues));
  }

  const defaultIntervalMs = parseDuration(defaults.interval ?? DEFAULT_INTERVAL);
  const defaultTimeoutMs = parseDuration(defaults.timeout ?? DEFAULT_TIMEOUT);

  const targets: ResolvedTargetBase[] = validated.targets.map((target) =>
    resolveTarget(target, defaults, defaultIntervalMs, defaultTimeoutMs, configDir),
  );

  return { configDir, dataDir, host, maxConcurrentChecks, port, retentionMs, targets };
}

function canRunSemanticValidation(value: unknown): boolean {
  return isPlainObject(value);
}

function dedupeIssues(issues: ConfigValidationIssue[]): ConfigValidationIssue[] {
  const seen = new Set<string>();
  const result: ConfigValidationIssue[] = [];
  for (const item of issues) {
    const key = `${item.code}:${item.path}:${item.message}:${item.targetName ?? ""}:${item.targetId ?? ""}`;
    if (seen.has(key)) continue;
    seen.add(key);
    result.push(item);
  }
  return result;
}

export { parseDuration } from "./utils";

function resolveMaxConcurrentChecks(runtime: EngineRuntimeConfig): number {
  if (runtime.maxConcurrentChecks === undefined) return DEFAULT_MAX_CONCURRENT_CHECKS;
  if (
    !isNumber(runtime.maxConcurrentChecks) ||
    !Number.isInteger(runtime.maxConcurrentChecks) ||
    runtime.maxConcurrentChecks <= 0
  )
    return DEFAULT_MAX_CONCURRENT_CHECKS;
  return runtime.maxConcurrentChecks;
}

function resolveRetention(runtime: EngineRuntimeConfig): number {
  return parseDuration(runtime.retention ?? DEFAULT_RETENTION);
}

function resolveTarget(
  target: RawTargetConfig,
  defaults: DefaultsConfig,
  defaultIntervalMs: number,
  defaultTimeoutMs: number,
  configDir: string,
): ResolvedTargetBase {
  const intervalMs = parseDuration(target.interval ?? defaults.interval ?? DEFAULT_INTERVAL);
  const timeoutMs = parseDuration(target.timeout ?? defaults.timeout ?? DEFAULT_TIMEOUT);

  const checker = checkerRegistry.get(target.type);
  const result = checker.resolve(target, { configDir, defaultIntervalMs, defaults, defaultTimeoutMs });

  result.intervalMs = intervalMs;
  result.timeoutMs = timeoutMs;
  result.description = target.description ?? null;

  return result;
}

function validateConfig(config: RawProbeConfig): ConfigValidationIssue[] {
  const issues: ConfigValidationIssue[] = [];
  if (!Array.isArray(config.targets) || config.targets.length === 0) {
    issues.push(issue("required", "targets", "配置文件必须包含至少一个 target"));
    return issues;
  }
  const ids = new Set<string>();
  const supportedTypes = checkerRegistry.supportedTypes;

  for (let i = 0; i < config.targets.length; i++) {
    const rawTarget = config.targets[i] as unknown;
    if (!isPlainObject(rawTarget)) {
      issues.push(issue("invalid-type", `targets[${i}]`, "必须为对象"));
      continue;
    }
    const raw = rawTarget as Record<string, unknown>;

    const id: unknown = raw["id"];
    if (!isString(id) || id.trim() === "") {
      issues.push(issue("required", `targets[${i}].id`, "缺少 id 字段"));
      continue;
    }

    if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(id)) {
      issues.push(issue("invalid-format", `targets[${i}].id`, "id 不符合命名规则", id));
    }

    const nameValue: unknown = raw["name"];
    const name = isString(nameValue) ? nameValue : id;

    if (isString(nameValue) && nameValue.trim() === "") {
      issues.push(issue("invalid-value", `targets[${i}].name`, "name 不能为空白", name));
    }

    const type: unknown = raw["type"];
    if (!isString(type)) {
      issues.push(issue("required", `targets[${i}].type`, "缺少 type 字段", name));
      continue;
    }

    if (!supportedTypes.includes(type)) {
      issues.push(
        issue(
          "unsupported-type",
          `targets[${i}].type`,
          `使用不支持的 type: "${type}"，支持: ${supportedTypes.join(", ")}`,
          name,
        ),
      );
    }

    const group: unknown = raw["group"];
    if (group !== undefined && !isString(group)) {
      issues.push(issue("invalid-type", `targets[${i}].group`, "必须为字符串", name));
    }

    if (ids.has(id)) {
      issues.push(issue("duplicate-id", `targets[${i}].id`, `target id 重复: "${id}"`, name));
    }

    ids.add(id);
  }

  for (const checker of checkerRegistry.definitions) {
    issues.push(...checker.validate({ defaults: config.defaults ?? {}, targets: config.targets }));
  }

  validateDurationValue(config.defaults?.interval, "defaults.interval", issues);
  validateDurationValue(config.defaults?.timeout, "defaults.timeout", issues);
  validateDurationValue(
    isString(config.runtime?.retention) ? config.runtime.retention : undefined,
    "runtime.retention",
    issues,
  );
  for (let i = 0; i < config.targets.length; i++) {
    const target = config.targets[i] as unknown;
    if (!isPlainObject(target)) continue;
    const targetRecord = target as Record<string, unknown>;
    const targetNameValue: unknown = targetRecord["name"];
    const targetIdValue: unknown = targetRecord["id"];
    const targetName = isString(targetNameValue)
      ? targetNameValue
      : isString(targetIdValue)
        ? targetIdValue
        : undefined;
    validateDurationValue(
      isString(targetRecord["interval"]) ? targetRecord["interval"] : undefined,
      `targets[${i}].interval`,
      issues,
      targetName,
    );
    validateDurationValue(
      isString(targetRecord["timeout"]) ? targetRecord["timeout"] : undefined,
      `targets[${i}].timeout`,
      issues,
      targetName,
    );
  }

  return issues;
}

function validateDurationValue(
  value: string | undefined,
  path: string,
  issues: ConfigValidationIssue[],
  targetName?: string,
): void {
  if (value === undefined) return;
  try {
    parseDuration(value);
  } catch (error) {
    issues.push(issue("invalid-duration", path, error instanceof Error ? error.message : "时长格式不合法", targetName));
  }
}
