// Node 22+. One check per invocation; your scheduler owns the cadence.
// REST needs no packages. MCP additionally needs @modelcontextprotocol/client@2.4.0.
import { createHash, randomUUID } from "node:crypto"
import { open, readFile, rename, unlink } from "node:fs/promises"
import { resolve } from "node:path"
import { pathToFileURL } from "node:url"

const slug = (value) => typeof value === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value)
const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0
const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex")
const fail = (code, message) => { throw new WatchError(code, message) }
export class WatchError extends Error {
  constructor(code, message) { super(message); this.code = code }
}

export function watchConfig(value) {
  if (!value || typeof value !== "object" || Array.isArray(value) ||
      Object.keys(value).some((key) => !["gpu", "count", "provider", "region", "maxNodeHourlyPrice"].includes(key)) ||
      !slug(value.gpu) || !Number.isInteger(value.count) || value.count < 1 || value.count > 10000 ||
      !positive(value.maxNodeHourlyPrice)) fail("invalid_config", "Use a canonical GPU slug, exact GPU count and positive maxNodeHourlyPrice in USD.")
  if (value.provider !== undefined && !slug(value.provider)) fail("invalid_config", "Use a canonical provider slug from list_providers.")
  if (value.region !== undefined && (typeof value.region !== "string" || !value.region.trim() || value.region.length > 100)) {
    fail("invalid_config", "Use an exact provider-reported region label from get_prices.")
  }
  return { gpu: value.gpu, count: value.count,
    ...(value.provider ? { provider: value.provider } : {}),
    ...(value.region ? { region: value.region.trim().toLowerCase() } : {}), maxNodeHourlyPrice: value.maxNodeHourlyPrice }
}

function trustedBase(value) {
  const url = new URL(value)
  if (url.username || url.password || url.search || url.hash || url.pathname !== "/" ||
      !(url.protocol === "https:" || url.protocol === "http:" && url.hostname === "127.0.0.1")) {
    fail("invalid_endpoint", "Use a trusted HTTPS origin or an isolated 127.0.0.1 fixture; no credentials in URLs.")
  }
  return url
}

function apiFailure(error) {
  const code = ["invalid_credential", "account_disabled", "quota_exceeded", "rate_limited", "bad_request", "not_found", "result_too_large", "enforcement_unavailable", "data_unavailable", "deadline_exceeded"].includes(error?.code) ? error.code : "request_failed"
  fail(code, "Request failed. Preserve the baseline; inspect get_usage and retry/reset guidance before another data call. No automatic replay was made.")
}

async function reader(base, key, transport) {
  const headers = { Authorization: `Bearer ${key}` }
  if (transport === "rest") return {
    close: () => Promise.resolve(),
    async call(operation, input = {}) {
      const url = new URL(operation === "get_usage" ? "/api/v1/usage" : "/api/v1/snapshot", base)
      for (const [name, value] of Object.entries(input)) url.searchParams.set(name, String(value))
      const response = await fetch(url, { headers, redirect: "error", signal: AbortSignal.timeout(10000) })
      const body = await response.json()
      if (!response.ok || body?.data?.error) apiFailure(body?.data?.error)
      if (body?.version !== "v1" || !Number.isFinite(Date.parse(body.generatedAt)) || !body.data || typeof body.data !== "object") {
        fail("invalid_response", "Invalid REST envelope; baseline preserved.")
      }
      return body.data
    },
  }
  if (transport !== "mcp") fail("invalid_config", "Transport must be rest or mcp.")
  const { Client, StreamableHTTPClientTransport } = await import("@modelcontextprotocol/client")
  const client = new Client({ name: "gpufinder-availability-watch", version: "1" }, {
    versionNegotiation: { mode: { pin: "2026-07-28" } },
  })
  let snapshotSent = false
  // This server uses JSON responses. Never follow a credential-bearing redirect.
  const connection = new StreamableHTTPClientTransport(new URL("/mcp", base), {
    requestInit: { headers },
    async fetch(input, init) {
      const signal = AbortSignal.any([init?.signal, AbortSignal.timeout(10000)].filter(Boolean))
      const request = new Request(input, { ...init, redirect: "error", signal })
      if (request.method === "POST") {
        const rpc = await request.clone().json()
        if (rpc.method === "tools/call" && rpc.params?.name === "get_market_snapshot") {
          if (snapshotSent) fail("replay_blocked", "A data request was already sent. Inspect usage before another data call.")
          snapshotSent = true
        }
      }
      return fetch(request)
    },
  })
  try { await client.connect(connection) } catch { await client.close(); fail("connection_failed", "MCP connection failed; baseline preserved.") }
  return {
    close: () => client.close(),
    async call(name, args = {}) {
      const result = await client.callTool({ name, arguments: args }, { signal: AbortSignal.timeout(10000) })
      const body = result.structuredContent
      if (result.isError || body?.error) apiFailure(body?.error)
      if (!body?.data || typeof body.data !== "object" || body.nextCursor) fail("invalid_response", "Expected a complete MCP snapshot; baseline preserved.")
      return body.data
    },
  }
}

function usageAvailable(data) {
  const monthly = data?.monthly
  if (monthly?.kind === "unlimited") return
  if (monthly?.kind !== "finite" || !Number.isSafeInteger(monthly.remaining) || monthly.remaining < 0) {
    fail("invalid_response", "Invalid usage response; no data request was made.")
  }
  if (monthly.remaining < 1) fail("quota_exceeded", "No monthly data calls remain. Pause the schedule until reset or arrange an allowance change; no data request was made.")
}

export function observation(snapshot, config, now = Date.now()) {
  const gpuSlug = typeof snapshot?.gpu === "string" ? snapshot.gpu.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") : ""
  const generated = Date.parse(snapshot?.generatedAt)
  if (gpuSlug !== config.gpu || snapshot?.count !== config.count || snapshot.priceCurrency !== "USD" ||
      !Number.isFinite(generated) || generated > now || now - generated > 6 * 3600000) {
    fail("invalid_response", "Snapshot identity or generation time is invalid; baseline preserved.")
  }
  const filters = snapshot.filters ?? {}
  if ((filters.provider ?? null) !== (config.provider ?? null) || (filters.region ?? null) !== (config.region ?? null)) {
    fail("scope_mismatch", "Server did not confirm this watch's provider/region scope; baseline preserved.")
  }
  if (!Object.hasOwn(snapshot, "cheapestAvailable")) fail("invalid_response", "Missing stock result; baseline preserved.")
  const offer = snapshot.cheapestAvailable
  if (offer === null) return { status: "no_confirmed_stock", offer: null }
  const checked = Date.parse(offer.availabilityCheckedAt)
  const maxHours = snapshot.availabilityFreshness?.maxAgeHours
  if (!["available", "limited"].includes(offer.availabilityStatus) || !positive(maxHours) || maxHours > 6 ||
      !Number.isFinite(checked) || checked > now || now - checked > maxHours * 3600000) {
    fail("stale_observation", "No fresh stock observation for the returned offer; baseline preserved.")
  }
  if (offer.gpuCount !== config.count || !positive(offer.wholeNodeHourlyPrice) || !positive(offer.perGpuHourlyPrice) ||
      Math.abs(offer.wholeNodeHourlyPrice / config.count - offer.perGpuHourlyPrice) > 1e-8 ||
      typeof offer.provider !== "string" || !offer.provider ||
      (config.provider && offer.providerSlug !== config.provider) ||
      !(offer.region === null || typeof offer.region === "string") ||
      (config.region && offer.region?.toLowerCase() !== config.region)) {
    fail("invalid_response", "Offer identity or node/GPU price units are invalid; baseline preserved.")
  }
  const selected = { provider: offer.provider, providerSlug: offer.providerSlug ?? null, region: offer.region, gpuCount: offer.gpuCount,
    wholeNodeHourlyPrice: offer.wholeNodeHourlyPrice, perGpuHourlyPrice: offer.perGpuHourlyPrice,
    availabilityStatus: offer.availabilityStatus, availabilityCheckedAt: offer.availabilityCheckedAt,
    outboundUrl: offer.outboundUrl ?? null, reliability: offer.reliability ?? null }
  return { status: offer.wholeNodeHourlyPrice <= config.maxNodeHourlyPrice ? "eligible" : "over_budget", offer: selected }
}

/** Observation times/history can advance without changing an actionable offer. */
export function observationSignature(value) {
  return hash(value.status === "eligible" ? { status: value.status,
    provider: value.offer.provider, region: value.offer.region, count: value.offer.gpuCount,
    nodePrice: value.offer.wholeNodeHourlyPrice } : { status: value.status })
}

async function previousState(path, watchHash) {
  let previous
  try { previous = JSON.parse(await readFile(path, "utf8")) } catch (error) {
    if (error?.code === "ENOENT") return null
    fail("invalid_state", "Cannot read the baseline. Restore it or choose a new state file; no data request was made.")
  }
  if (previous?.version !== 1 || previous.watchHash !== watchHash || !/^[a-f0-9]{64}$/.test(previous.signature) ||
      !Number.isFinite(Date.parse(previous.generatedAt))) {
    fail("invalid_state", "Baseline does not match this endpoint/watch configuration. Choose a new state file; no data request was made.")
  }
  return previous
}

async function atomicState(path, state) {
  const temp = `${path}.${randomUUID()}.tmp`
  try {
    const handle = await open(temp, "wx", 0o600)
    try { await handle.writeFile(JSON.stringify(state, null, 2) + "\n") } finally { await handle.close() }
    await rename(temp, path)
  } finally { await unlink(temp).catch(() => undefined) }
}

/** Returns one baseline/change event, or null for an unchanged successful check. */
/** @param {{config: unknown, statePath: string, transport?: string, baseUrl?: string, key?: string, now?: number}} options */
export async function runWatch({ config: raw, statePath, transport = "rest", baseUrl = "https://gpufinder.dev", key, now }) {
  const config = watchConfig(raw)
  const base = trustedBase(baseUrl)
  if (typeof key !== "string" || !key.trim()) fail("missing_key", "Supply GPUFINDER_API_KEY from your secret manager.")
  const path = resolve(statePath)
  const watchHash = hash({ endpoint: base.href, config })
  let lock
  try { lock = await open(`${path}.lock`, "wx", 0o600) } catch {
    fail("state_locked", "State is locked or not writable. Do not overlap runs; remove an abandoned lock only after checking its process.")
  }
  let connection
  try {
    await lock.writeFile(String(process.pid))
    const previous = await previousState(path, watchHash)
    connection = await reader(base, key, transport)
    usageAvailable(await connection.call("get_usage"))
    const { maxNodeHourlyPrice: _budget, ...input } = config
    const snapshot = await connection.call("get_market_snapshot", input)
    now = now ?? Date.now()
    const value = observation(snapshot, config, now)
    if (previous && Date.parse(snapshot.generatedAt) < Date.parse(previous.generatedAt)) {
      fail("older_snapshot", "Snapshot predates the baseline; baseline preserved.")
    }
    const signature = observationSignature(value)
    const event = !previous ? "baseline" : previous.signature === signature ? null : "changed"
    const state = { version: 1, watchHash, generatedAt: snapshot.generatedAt,
      checkedAt: new Date(now).toISOString(), signature, observation: value }
    await atomicState(path, state)
    return event ? { event, watch: config, checkedAt: state.checkedAt, observation: value } : null
  } finally {
    await connection?.close().catch(() => undefined)
    await lock.close()
    await unlink(`${path}.lock`)
  }
}

async function main() {
  const args = process.argv.slice(2)
  const options = {}
  for (let i = 0; i < args.length; i += 2) {
    if (!["--config", "--state", "--transport"].includes(args[i]) || !args[i + 1] || options[args[i]]) {
      fail("invalid_arguments", "Usage: node availability-watch.mjs --config watch.json --state watch-state.json [--transport rest|mcp]")
    }
    options[args[i]] = args[i + 1]
  }
  if (!options["--config"] || !options["--state"]) fail("invalid_arguments", "Supply --config and --state paths.")
  const config = JSON.parse(await readFile(options["--config"], "utf8"))
  const key = process.env.GPUFINDER_API_KEY ?? (process.env.GPUFINDER_API_KEY_FILE
    ? (await readFile(process.env.GPUFINDER_API_KEY_FILE, "utf8")).trim() : undefined)
  const result = await runWatch({ config, statePath: options["--state"], transport: options["--transport"] ?? "rest",
    baseUrl: process.env.GPUFINDER_BASE_URL, key })
  if (result) console.log(JSON.stringify(result))
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  main().catch((error) => {
    // Never print a raw SDK/transport error, request headers or credential.
    console.error(JSON.stringify({ error: error instanceof WatchError ? { code: error.code, message: error.message } :
      { code: "check_failed", message: "Check failed; baseline preserved. Inspect usage before another data call." } }))
    process.exitCode = 1
  })
}
