import { createHash } from "node:crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";

import { compileAssetArchive, compileStaticStickerCatalog } from "../packages/asset-compiler/dist/index.js";
import { createP0aColorCardRenderPlans } from "../packages/asset-renderer/dist/index.js";
import {
  P0A_COLOR_CARD_IDS,
  P0A_COMPLEX_RELEASE_VERSION,
  P0A_DYNAMIC_STICKER_IDS,
  P0A_REQUIRED_FONT_PANEL_IDS,
  P0A_STATIC_STICKER_RELEASE_VERSION,
  P0A_TEXT_TEMPLATE_IDS,
  createP0aPublicManifest,
} from "../packages/template-registry/dist/index.js";

const runDirectory = resolve(process.env.DADA_WP5_03_RUN_DIRECTORY ?? "artifacts/tdd/wp5-03-local");
const whiteDirectory = resolve(process.env.DADA_WP5_03_WHITE_EVIDENCE_DIR ?? join(runDirectory, "cases", "TDD-WP5-WHITE-001-p0a-allowlist"));
const colorDirectory = resolve(process.env.DADA_WP5_03_COLOR_EVIDENCE_DIR ?? join(runDirectory, "cases", "TDD-WP5-COL-001-four-layouts"));
const replicationRoot = resolve(process.env.DADA_REPLICATION_ASSET_ROOT ?? join(homedir(), "Desktop", "sticker_web_replication_assets"));
const handoffManifest = resolve(process.env.DADA_COMPLEX_ASSET_MANIFEST ?? join(replicationRoot, "sticker_web_handoff", "sticker_web_catalog_manifest.json"));
const stickerRoot = resolve(process.env.DADA_STATIC_STICKER_ROOT ?? join(replicationRoot, "sticker_normal"));
if (!existsSync(handoffManifest)) throw new Error("normalized complex asset handoff is unavailable");
if (!existsSync(stickerRoot)) throw new Error("static sticker source is unavailable");

const complexDirectory = resolve(runDirectory, "inputs", "complex");
const staticDirectory = resolve(runDirectory, "inputs", "static");
const normalizedHandoffDirectory = resolve(runDirectory, "inputs", "normalized-handoff");
mkdirSync(whiteDirectory, { recursive: true });
mkdirSync(colorDirectory, { recursive: true });

const sourceHandoff = JSON.parse(readFileSync(handoffManifest, "utf8"));
const normalizedHandoff = {
  ...sourceHandoff,
  web_handoff: "STICKER_WEB_REPLICATION_HANDOFF.md",
  validation: "sticker_archive_validation_20260722.json",
  collections: sourceHandoff.collections
    .filter((collection) => collection.id !== "normal_stickers")
    .map((collection) => ({
      ...collection,
      root: resolve(dirname(handoffManifest), collection.root),
    })),
};
const normalizedHandoffPath = resolve(normalizedHandoffDirectory, "sticker_web_catalog_manifest.normalized.json");
mkdirSync(normalizedHandoffDirectory, { recursive: true });
copyFileSync(resolve(dirname(handoffManifest), sourceHandoff.web_handoff), resolve(normalizedHandoffDirectory, normalizedHandoff.web_handoff));
copyFileSync(resolve(dirname(handoffManifest), sourceHandoff.validation), resolve(normalizedHandoffDirectory, normalizedHandoff.validation));
writeFileSync(normalizedHandoffPath, `${JSON.stringify(normalizedHandoff, null, 2)}\n`);

const complex = compileAssetArchive({
  manifestPath: normalizedHandoffPath,
  outputDirectory: complexDirectory,
  releaseVersion: P0A_COMPLEX_RELEASE_VERSION,
});
const staticResult = compileStaticStickerCatalog({
  expectedCount: 1_407,
  outputDirectory: staticDirectory,
  releaseVersion: P0A_STATIC_STICKER_RELEASE_VERSION,
  sourceRoot: stickerRoot,
});
const publicManifest = createP0aPublicManifest({
  complexManifest: complex.manifest,
  staticCatalog: staticResult.catalog,
});

function stableValue(value) {
  if (Array.isArray(value)) return value.map(stableValue);
  if (!value || typeof value !== "object") return value;
  return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stableValue(value[key])]));
}

function stableJson(value) {
  return `${JSON.stringify(stableValue(value), null, 2)}\n`;
}

function writeJson(path, value) {
  mkdirSync(resolve(path, ".."), { recursive: true });
  writeFileSync(path, stableJson(value));
}

const manifestPayload = stableJson(publicManifest);
const manifest = {
  ...publicManifest,
  manifest_sha256: createHash("sha256").update(manifestPayload).digest("hex").toUpperCase(),
};
const familyCounts = Object.fromEntries(["text_template", "font_panel", "color_card", "interactive_sticker"].map((family) => [
  family,
  complex.manifest.items.filter((item) => item.family === family).length,
]));
const fullP0Enabled = complex.manifest.items.filter((item) => item.release_tier === "full_p0" && item.release_status === "enabled").length;
const publicJson = JSON.stringify(manifest);
const hiddenIds = ["FLOWER009", "H009", "TAG008", "SIMPLE009", "COLOR003", "DYN005"];
const response = {
  counts: manifest.counts,
  full_p0_enabled: fullP0Enabled,
  hidden_ids_absent: hiddenIds.every((id) => !publicJson.includes(id)),
  no_absolute_paths: !/[A-Za-z]:[\\/]/.test(publicJson),
  release_tier: manifest.release_tier,
  status: "passed",
};
const registrationValidation = {
  allowlist: {
    color_cards: P0A_COLOR_CARD_IDS,
    dynamic_stickers: P0A_DYNAMIC_STICKER_IDS,
    font_panel_items: P0A_REQUIRED_FONT_PANEL_IDS,
    text_templates: P0A_TEXT_TEMPLATE_IDS,
  },
  full_registry_counts: familyCounts,
  full_registry_items: complex.manifest.items.length,
  full_p0_enabled: fullP0Enabled,
  source_mutations: complex.report.source_mutations + staticResult.report.source_mutations,
  static_parts: Object.keys(staticResult.catalog.part_counts).length,
  static_stickers: staticResult.catalog.count,
  status: response.hidden_ids_absent && response.no_absolute_paths && fullP0Enabled === 0 ? "passed" : "failed",
};
if (registrationValidation.status !== "passed") throw new Error("P0-A registration validation failed");

writeJson(resolve(whiteDirectory, "manifest.json"), manifest);
writeJson(resolve(whiteDirectory, "response.json"), response);
writeJson(resolve(whiteDirectory, "registration-validation.json"), registrationValidation);

const palette = ["#102030", "#405060", "#708090", "#A0B0C0", "#D0E0F0"];
const renderPlans = createP0aColorCardRenderPlans(palette);
writeJson(resolve(colorDirectory, "manifest.json"), {
  assets: manifest.assets.color_cards,
  count: manifest.counts.color_cards,
  release_tier: manifest.release_tier,
  schema_version: manifest.schema_version,
});
writeJson(resolve(colorDirectory, "palette.json"), {
  palette,
  renderers: renderPlans.map((plan) => ({ card_id: plan.cardId, renderer_name: plan.rendererName, style_id: plan.styleId })),
  same_palette_snapshot: renderPlans.every((plan) => plan.palette === renderPlans[0].palette),
  status: "passed",
});

console.log(JSON.stringify({
  full_registry_counts: familyCounts,
  public_counts: manifest.counts,
  source_mutations: registrationValidation.source_mutations,
  status: "passed",
}, null, 2));
