/**
 * Re-record a fixture after a store changes its markup:
 *   npm run record <storeId> [partNumber]
 * Writes fixtures/<store>/<CANONICAL>.html, then run `npm test` and fix selectors until green.
 * A walled (onDemand) store records through the resident browser — it must be running.
 */
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { getAdapter } from "../src/core/registry.js";
import { normalizeQuery } from "../src/core/normalize.js";
import { config } from "../src/core/config.js";
import { PoliteHttp } from "../src/core/politeHttp.js";
import { BrowserHub } from "../src/core/browserHub.js";
import type { FetchContext } from "../src/core/types.js";

const [storeId, rawQuery = "W 712/52"] = process.argv.slice(2);
const adapter = storeId ? getAdapter(storeId) : undefined;
if (!adapter) {
  console.error(`Usage: npm run record <storeId> [partNumber] — unknown store "${storeId ?? ""}"`);
  process.exit(1);
}
const q = normalizeQuery(rawQuery);
if (!q) {
  console.error(`Query too short: "${rawQuery}"`);
  process.exit(1);
}

const browser = new BrowserHub(config.browser);
const ctx: FetchContext = { http: new PoliteHttp(), browser };

const raw = await adapter.fetchRaw(q, ctx);
const dir = path.join(config.rootDir, "fixtures", adapter.id);
mkdirSync(dir, { recursive: true });
const file = path.join(dir, `${q.canonical}.${adapter.fixtureExt ?? "html"}`);
writeFileSync(file, raw);

const offers = adapter.parse(raw, q);
console.log(`Recorded ${file} (${raw.length} bytes); current selectors parse ${offers.length} offer(s).`);
await browser.close();
