import type { AppConfig } from "@qjclaw/shared-types"

function matchesSmokeExpertModelConfig(
  current: AppConfig["expertModelConfig"] | null | undefined,
  expected: AppConfig["expertModelConfig"]
): boolean {
  if (!current) {
    return false
  }

  const modelConfigMatches = (["image", "video", "copywriting"] as const).every((kind) => {
    const currentEntry = current[kind]
    const expectedEntry = expected[kind]
    return currentEntry?.baseUrl === expectedEntry.baseUrl
      && Boolean(currentEntry?.apiKeyConfigured) === Boolean(expectedEntry.apiKeyConfigured)
      && (currentEntry?.modelId ?? "") === (expectedEntry.modelId ?? "")
  })

  if (!modelConfigMatches) {
    return false
  }

  return current.digitalHuman.volcAccessKeyConfigured === expected.digitalHuman.volcAccessKeyConfigured
    && current.digitalHuman.volcSecretKeyConfigured === expected.digitalHuman.volcSecretKeyConfigured
    && current.digitalHuman.qiniuAccessKeyConfigured === expected.digitalHuman.qiniuAccessKeyConfigured
    && current.digitalHuman.qiniuSecretKeyConfigured === expected.digitalHuman.qiniuSecretKeyConfigured
}

export async function waitForSmokeConfigPublish(
  expected: AppConfig["expertModelConfig"],
  timeoutMs = 5000
): Promise<void> {
  const started = Date.now()
  while (Date.now() - started < timeoutMs) {
    if (matchesSmokeExpertModelConfig(window.__QJC_SMOKE__?.modelConfig, expected)) {
      return
    }
    await new Promise<void>((resolve) => {
      window.setTimeout(resolve, 50)
    })
  }

  throw new Error("Smoke settings config was not published in time.")
}
