// 生成一对 HEIC + MOV（共享 ContentIdentifier），用于 exiftool 配对校验
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const TD = path.join(__dirname, '..', 'testdata');
const OUT = path.join(__dirname, 'test-output', 'heic-mode');
mkdirSync(OUT, { recursive: true });

// Node 下为 wasm 编码器提供本地文件（浏览器走 fetch）
const realFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
  if (String(url).includes('apple-hdr-heic.wasm')) {
    const data = readFileSync(path.join(__dirname, 'vendor', 'apple-hdr-heic.wasm'));
    return { ok: true, arrayBuffer: async () => data };
  }
  return realFetch(url);
};

const { encodeHeicWithLivePhotoMeta } = await import(pathToFileURL(path.join(__dirname, 'js', 'heic.js')).href);
const { mp4ToLivePhotoMov } = await import(pathToFileURL(path.join(__dirname, 'js', 'mov.js')).href);
const { extractExifFromJpeg } = await import(pathToFileURL(path.join(__dirname, 'js', 'exif.js')).href);

const UUID = 'AAAAAAAA-BBBB-4CCC-9DDD-EEEEFFFF0000';
const date = new Date('2025-10-12T23:36:14+13:00');

// --- MOV ---
// 注意：必须用合法 H.264 视频。`video_tail.mp4` 仅 1312 字节、是异常截断的合成垃圾，
// 产物 ffprobe 会报 "wrong sample count, Picture size 0x0"，Synology 索引器会跳过配对。
// `real.mp4` 是 ffmpeg 生成的 320×240 / 3 秒 / 15fps 合法样本。
const mp4 = readFileSync(path.join(TD, 'real.mp4'));
const { bytes: mov } = mp4ToLivePhotoMov(new Uint8Array(mp4), UUID, date, {
  photoWidth: 320, photoHeight: 240,
  exifMeta: { make: 'Apple', model: 'iPhone 15 Pro Max', software: '17.0', iso6709: '+37.7890+175.2995+035.332/' },
  camera: { lensModel: 'iPhone 15 Pro Max back camera 6.765mm f/1.78', focal35mmEquivalent: '23', lensIrisFNumber: 'F1.78', makerNote74: 2, makerNote97: 24 },
});
writeFileSync(path.join(OUT, 'hw_livephoto.mov'), Buffer.from(mov));

// --- HEIC ---
const jpeg = readFileSync(path.join(TD, 'hw_livephoto.jpg'));
const { parseMotionPhoto } = await import(pathToFileURL(path.join(__dirname, 'js', 'motionphoto.js')).href);
const parsed = parseMotionPhoto(new Uint8Array(jpeg));
const exifTiff = extractExifFromJpeg(parsed.image);

const W = 400, H = 300;
const rgba = new Uint8Array(W * H * 4);
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
  const i = (y * W + x) * 4;
  rgba[i] = (x * 255 / W) | 0; rgba[i + 1] = (y * 255 / H) | 0; rgba[i + 2] = 90; rgba[i + 3] = 255;
}
const heic = await encodeHeicWithLivePhotoMeta(rgba, W, H, 90, exifTiff, UUID);
writeFileSync(path.join(OUT, 'hw_livephoto.heic'), Buffer.from(heic));

function ftypInfo(b) {
  const size = b.readUInt32BE(0);
  const pl = b.subarray(8, size);
  const compat = [];
  for (let i = 8; i + 4 <= pl.length; i += 4) compat.push(pl.toString('utf-8', i, i + 4));
  return pl.toString('utf-8', 0, 4) + ' / [' + compat.join(',') + '] (size=' + size + ')';
}

console.log('UUID        : ' + UUID);
console.log('HEIC        : ' + heic.length + ' 字节   ftyp=' + ftypInfo(Buffer.from(heic)));
console.log('MOV         : ' + mov.length + ' 字节   ftyp=' + ftypInfo(Buffer.from(mov)));
console.log();
console.log('已写出到 ' + OUT);
