import fs from "node:fs";
import path from "node:path";
import process from "node:process";

const repoRoot = process.cwd();
const failures = [];

function read(relativePath) {
  return fs.readFileSync(path.join(repoRoot, relativePath), "utf8");
}

function assertMatch(label, content, pattern) {
  if (!pattern.test(content)) {
    failures.push(label);
  }
}

function assertNoMatch(label, content, pattern) {
  if (pattern.test(content)) {
    failures.push(label);
  }
}

const serverConnection = read("src/api/serverConnection.ts");
const generationClient = read("src/api/aiGenerationClient.ts");
const ecommerceVideoService = read("src/features/ecommerce/ecommerceVideoService.ts");
const workbenchPersistence = read("src/features/workbench/workbenchResultPersistence.ts");

assertMatch(
  "serverConnection must build same-origin /api URLs",
  serverConnection,
  /return\s+`\/api\/\$\{cleanPath\}`;/,
);
assertNoMatch(
  "frontend generation flow must not use fixed VITE environment config",
  `${serverConnection}\n${generationClient}`,
  /\b(?:import\.meta\.env|VITE_[A-Z0-9_]+)\b/,
);
assertNoMatch(
  "frontend generation flow must not call provider hosts directly",
  generationClient,
  /dashscope\.aliyuncs\.com|\/dashscope-api\b|Bearer\s+sk-/i,
);
assertMatch("image generation must go through the app API", generationClient, /buildApiUrl\("ai\/image"\)/);
assertMatch("video generation must go through the app API", generationClient, /serverRequest<\{ taskId: string \}>\("ai\/video"/);
assertMatch("binary uploads must go through the app OSS API", generationClient, /buildApiUrl\("oss\/upload-binary"\)/);
assertMatch("URL uploads must go through the app OSS API", generationClient, /serverRequest<\{ url: string; signedUrl\?: string; ossKey\?: string \}>\("oss\/upload-by-url"/);
assertMatch(
  "ecommerce video history must durable-copy media before saving",
  ecommerceVideoService,
  /buildDurableVideoHistoryPayload\(payload\)/,
);
assertMatch(
  "ecommerce video history must filter temporary provider URLs on read",
  ecommerceVideoService,
  /items:\s*history\.items\.map\(removeTemporaryHistoryUrls\)/,
);
assertMatch(
  "workbench results must persist generated media through OSS",
  workbenchPersistence,
  /uploadAssetByUrl\(/,
);

if (failures.length) {
  console.error("Mocked generation smoke check failed:");
  for (const failure of failures) {
    console.error(`- ${failure}`);
  }
  process.exit(1);
}

console.log("Mocked generation smoke check passed.");
