import {execFileSync} from 'node:child_process';
import {readFileSync, writeFileSync, unlinkSync} from 'node:fs';
import {dirname, join} from 'node:path';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';

const here = dirname(fileURLToPath(import.meta.url));
const mainPath = join(here, '.fallback-main.jpg');
const thumbPath = join(here, '.fallback-thumb.jpg');
const outputPath = join(here, 'fallback-stale-thumbnail.jpg');
const dataPath = join(here, 'fallback-data.mjs');

function makeImage(path, width, height, variant) {
  const main = variant === 'main';
  const scale = width / 640;
  const draw = [
    `fill #111820 rectangle 0,0 ${width},${height}`,
    `fill #23313b rectangle ${Math.round(34*scale)},${Math.round(34*scale)} ${Math.round(606*scale)},${Math.round(366*scale)}`,
    `fill ${main ? '#b94735' : '#315f91'} rectangle ${Math.round(58*scale)},${Math.round(58*scale)} ${Math.round(582*scale)},${Math.round(342*scale)}`,
    `fill #efe4c8 rectangle ${Math.round(84*scale)},${Math.round(92*scale)} ${Math.round(556*scale)},${Math.round(304*scale)}`,
    `fill #111820 rectangle ${Math.round(110*scale)},${Math.round(118*scale)} ${Math.round(530*scale)},${Math.round(278*scale)}`,
    `stroke #efe4c8 stroke-width ${Math.max(1,Math.round(5*scale))} line ${Math.round(126*scale)},${Math.round(256*scale)} ${Math.round(514*scale)},${Math.round(140*scale)}`,
    `stroke ${main ? '#ffcc66' : '#8fd4ff'} stroke-width ${Math.max(1,Math.round(12*scale))} line ${Math.round(126*scale)},${Math.round(140*scale)} ${Math.round(514*scale)},${Math.round(256*scale)}`,
    `fill ${main ? '#ffcc66' : '#8fd4ff'} circle ${Math.round((main?458:182)*scale)},${Math.round(198*scale)} ${Math.round((main?492:216)*scale)},${Math.round(198*scale)}`,
    `fill #efe4c8 polygon ${Math.round(286*scale)},${Math.round(188*scale)} ${Math.round(320*scale)},${Math.round(128*scale)} ${Math.round(354*scale)},${Math.round(188*scale)} ${Math.round(320*scale)},${Math.round(248*scale)}`
  ].join(' ');
  execFileSync('convert', ['-size', `${width}x${height}`, 'xc:#111820', '-draw', draw, '-strip', '-sampling-factor', '2x2', '-quality', main ? '90' : '82', '-interlace', 'none', path]);
}

const ascii = (text, count) => {
  const out = Buffer.alloc(count);
  Buffer.from(text, 'ascii').copy(out, 0, 0, Math.min(text.length, count - 1));
  return out;
};
const short = n => { const b = Buffer.alloc(2); b.writeUInt16LE(n); return b; };
const long = n => { const b = Buffer.alloc(4); b.writeUInt32LE(n); return b; };
const rationals = values => {
  const b = Buffer.alloc(values.length * 8);
  values.forEach(([n,d], i) => { b.writeUInt32LE(n, i * 8); b.writeUInt32LE(d, i * 8 + 4); });
  return b;
};
const entry = (tag, type, count, value) => ({tag,type,count,value});
const dirSize = entries => 2 + entries.length * 12 + 4;

function buildExif(thumbnail) {
  const maker = Buffer.from(Array.from({length:64}, (_, i) => (i * 73 + 19) & 255));
  const ifd0 = [
    entry(256,4,1,long(640)), entry(257,4,1,long(400)), entry(274,3,1,short(1)),
    entry(306,2,20,ascii('2026:08:09 09:08:07',20)), entry(34665,4,1,null), entry(34853,4,1,null)
  ];
  const exif = [
    entry(36867,2,20,ascii('2026:08:09 08:01:02',20)), entry(36868,2,20,ascii('2026:08:09 08:02:03',20)),
    entry(36880,2,7,ascii('+10:00',7)), entry(36881,2,7,ascii('+09:30',7)), entry(36882,2,7,ascii('+09:30',7)),
    entry(37500,7,maker.length,maker), entry(37520,2,4,ascii('654',4)),
    entry(37521,2,4,ascii('125',4)), entry(37522,2,4,ascii('250',4)),
    entry(40962,4,1,long(640)), entry(40963,4,1,long(400))
  ];
  const gps = [
    entry(0,1,4,Buffer.from([2,3,0,0])), entry(1,2,2,ascii('N',2)), entry(2,5,3,rationals([[0,1],[0,1],[0,1]])),
    entry(3,2,2,ascii('E',2)), entry(4,5,3,rationals([[0,1],[0,1],[0,1]])),
    entry(7,5,3,rationals([[22,1],[34,1],[56,1]])), entry(29,2,11,ascii('2026:08:08',11))
  ];
  const ifd1 = [
    entry(256,4,1,long(160)), entry(257,4,1,long(100)), entry(259,3,1,short(6)), entry(274,3,1,short(1)),
    entry(306,2,20,ascii('2026:08:09 07:55:00',20)), entry(513,4,1,long(0)), entry(514,4,1,long(thumbnail.length))
  ];
  [ifd0,exif,gps,ifd1].forEach(list => list.sort((a,b) => a.tag - b.tag));
  const offsets = {ifd0:8};
  offsets.exif = offsets.ifd0 + dirSize(ifd0);
  offsets.gps = offsets.exif + dirSize(exif);
  offsets.ifd1 = offsets.gps + dirSize(gps);
  let dataCursor = offsets.ifd1 + dirSize(ifd1);
  ifd0.find(e => e.tag === 34665).value = long(offsets.exif);
  ifd0.find(e => e.tag === 34853).value = long(offsets.gps);
  const external = [];
  for (const list of [ifd0,exif,gps,ifd1]) for (const item of list) {
    const bytes = item.value;
    if (bytes.length > 4) {
      if (dataCursor & 1) dataCursor++;
      item.dataOffset = dataCursor;
      external.push(item);
      dataCursor += bytes.length;
    }
  }
  if (dataCursor & 1) dataCursor++;
  const thumbOffset = dataCursor;
  ifd1.find(e => e.tag === 513).value = long(thumbOffset);
  const tiff = Buffer.alloc(thumbOffset + thumbnail.length);
  tiff.write('II', 0, 'ascii');
  tiff.writeUInt16LE(42, 2);
  tiff.writeUInt32LE(offsets.ifd0, 4);
  function writeDir(list, offset, next) {
    tiff.writeUInt16LE(list.length, offset);
    list.forEach((item, i) => {
      const at = offset + 2 + i * 12;
      tiff.writeUInt16LE(item.tag, at);
      tiff.writeUInt16LE(item.type, at + 2);
      tiff.writeUInt32LE(item.count, at + 4);
      if (item.value.length <= 4) item.value.copy(tiff, at + 8);
      else tiff.writeUInt32LE(item.dataOffset, at + 8);
    });
    tiff.writeUInt32LE(next, offset + 2 + list.length * 12);
  }
  writeDir(ifd0, offsets.ifd0, offsets.ifd1);
  writeDir(exif, offsets.exif, 0);
  writeDir(gps, offsets.gps, 0);
  writeDir(ifd1, offsets.ifd1, 0);
  external.forEach(item => item.value.copy(tiff, item.dataOffset));
  thumbnail.copy(tiff, thumbOffset);
  return Buffer.concat([Buffer.from('Exif\0\0', 'binary'), tiff]);
}

function sha(bytes) { return createHash('sha256').update(bytes).digest('hex'); }

try {
  makeImage(mainPath, 640, 400, 'main');
  makeImage(thumbPath, 160, 100, 'thumb');
  const main = readFileSync(mainPath);
  const thumbnail = readFileSync(thumbPath);
  if (main[0] !== 0xff || main[1] !== 0xd8 || thumbnail[0] !== 0xff || thumbnail[1] !== 0xd8) throw new Error('ImageMagick did not produce JPEG SOI markers');
  const payload = buildExif(thumbnail);
  const declared = payload.length + 2;
  if (declared > 65535) throw new Error(`APP1 payload too large: ${declared}`);
  const app1 = Buffer.alloc(4);
  app1[0] = 0xff; app1[1] = 0xe1; app1.writeUInt16BE(declared, 2);
  const output = Buffer.concat([main.subarray(0,2), app1, payload, main.subarray(2)]);
  writeFileSync(outputPath, output);
  const moduleText = [
    'export const FALLBACK_NAME = "fallback-stale-thumbnail.jpg";',
    'export const FALLBACK_LAST_MODIFIED = Date.UTC(2026, 7, 9, 9, 8, 7, 654);',
    `export const FALLBACK_SIZE = ${output.length};`,
    `export const FALLBACK_SHA256 = "${sha(output)}";`,
    `export const FALLBACK_THUMBNAIL_SHA256 = "${sha(thumbnail)}";`,
    `export const FALLBACK_BASE64 = "${output.toString('base64')}";`,
    ''
  ].join('\n');
  writeFileSync(dataPath, moduleText);
  process.stdout.write(JSON.stringify({file:outputPath,size:output.length,sha256:sha(output),thumbnailBytes:thumbnail.length,thumbnailSha256:sha(thumbnail)}, null, 2) + '\n');
} finally {
  for (const path of [mainPath, thumbPath]) { try { unlinkSync(path); } catch {} }
}
