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

const assetRoot = process.env.DADA_TEXT_ASSET_ROOT ?? resolve(homedir(), "Desktop", "sticker_text");
const fontRoot = resolve(assetRoot, "字体", "面板全量采集", "font_panel_full_20260722", "resources", "font_packages", "FONT081_Lexend Deca");
const metadataPath = resolve(fontRoot, "metadata.json");
const packagePath = resolve(fontRoot, "font_package.ztf");
const fontPath = resolve(fontRoot, "font_files", "02034l0o6r57rxed4027b5689e0dxe7e142r0vi8920akeqto.ttf");

if (![metadataPath, packagePath, fontPath].every(existsSync)) throw new Error("FONT081 archived source is unavailable.");
const metadata = JSON.parse(readFileSync(metadataPath, "utf8"));
const packageBytes = readFileSync(packagePath);
const fontBytes = readFileSync(fontPath);
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex").toUpperCase();
const signature = fontBytes.subarray(0, 4).toString("hex").toUpperCase();
const validSignature = ["00010000", "4F54544F", "74746366"].includes(signature);
const packageSha256 = hash(packageBytes);
const expectedPackageSha256 = String(metadata.local_sha256 ?? "").toUpperCase();
if (metadata.candidate_id !== "FONT081" || metadata.font_family !== "Lexend Deca"
  || metadata.resource_status !== "verified_extracted" || packageSha256 !== expectedPackageSha256 || !validSignature) {
  throw new Error("FONT081 archived source verification failed.");
}

const result = {
  extracted_font_bytes: fontBytes.length,
  extracted_font_sha256: hash(fontBytes),
  fallback: null,
  font_family: metadata.font_family,
  font_id: metadata.candidate_id,
  package_sha256: packageSha256,
  package_status: metadata.package_status,
  resource_status: metadata.resource_status,
  sfnt_signature: signature,
  source_access: "read_only_normative_archive",
  status: "passed",
};
if (process.env.DADA_FONT_SOURCE_EVIDENCE) writeFileSync(process.env.DADA_FONT_SOURCE_EVIDENCE, `${JSON.stringify(result, null, 2)}\n`);
console.log(JSON.stringify(result, null, 2));
