import { isPlainObject } from "es-toolkit";

import type { CheckerRegistry } from "./runner/registry";
import type { ConfigValidationIssue } from "./schema/issues";
import type { AuthoringProbeConfig, NormalizedProbeConfig } from "./schema/types";
import type { RawTargetConfig } from "./types";

import { checkerRegistry } from "./runner";
import { resolveVariables } from "./variables";

export function normalizeAuthoringConfig(
  config: unknown,
  registry: CheckerRegistry = checkerRegistry,
): {
  config: unknown;
  issues: ConfigValidationIssue[];
} {
  const variableResult = resolveVariables(config);
  if (!isPlainObject(variableResult.config)) {
    return variableResult;
  }

  const normalized = { ...(variableResult.config as Record<string, unknown>) };
  delete normalized["variables"];
  if (Array.isArray(normalized["targets"])) {
    normalized["targets"] = normalized["targets"].map((target) => normalizeTarget(target, registry));
  }

  return { config: normalized, issues: variableResult.issues };
}

function normalizeTarget(target: unknown, registry: CheckerRegistry): unknown {
  if (!isPlainObject(target)) return target;
  const result = { ...(target as RawTargetConfig) };
  const type = result.type;
  if (typeof type !== "string") return result;
  const checker = registry?.tryGet(type);
  if (!checker) return result;
  return checker.normalize(result);
}

export type { AuthoringProbeConfig, NormalizedProbeConfig };
