import { PDFDocument, degrees } from 'pdf-lib';
import { text, choice, file } from './common.js';

export async function loadPDF(file) {
  try { const doc = await PDFDocument.load(await file.arrayBuffer(), { updateMetadata: false }); if (doc.getPageCount() < 1 || doc.getPageCount() > 100) throw new Error('pages'); return doc; }
  catch { throw new Error('PDF 损坏、已加密或页数不在 1–100 页范围。'); }
}
export function pageIndices(value, count) {
  const out = [];
  for (const part of value.split(',')) {
    const match = part.trim().match(/^(\d+)(?:\s*-\s*(\d+))?$/); if (!match) throw new Error('页码格式应为 1,3-5。');
    const a = Number(match[1]), b = Number(match[2] || match[1]); if (a < 1 || b < a || b > count || b - a > 100) throw new Error(`页码应在 1–${count} 范围内,区间需递增。`);
    for (let i = a; i <= b; i++) out.push(i - 1); if (out.length > 100) throw new Error('输出不能超过 100 页。');
  }
  return out;
}
export const pdfFile = async (doc, name = 'result.pdf') => file(new Blob([await doc.save()], { type: 'application/pdf' }), name, `${doc.getPageCount()} 页`);
const fields = {
  'pdf-merge': [], 'pdf-extract': [text('pages', '提取页码', '1')],
  'pdf-organize': [text('pages', '输出页序(可重复)', '1'), choice('rotation', '附加顺时针旋转', [['0', '0°'], ['90', '90°'], ['180', '180°'], ['270', '270°']])],
  'pdf-resize': [choice('paper', '纸张', [['a4', 'A4'], ['letter', 'Letter']]), choice('orientation', '方向', [['portrait', '纵向'], ['landscape', '横向']])],
};
export function getImplementation(id) {
  return { fields: fields[id], async run({ files, values: v }) {
    const docs = []; for (const f of files) docs.push(await loadPDF(f)); const out = await PDFDocument.create();
    if (id === 'pdf-merge') {
      if (docs.length < 2) throw new Error('请至少选择两份 PDF。'); if (docs.reduce((n, d) => n + d.getPageCount(), 0) > 100) throw new Error('合并输出不能超过 100 页。');
      for (const doc of docs) for (const page of await out.copyPages(doc, doc.getPageIndices())) out.addPage(page);
    } else if (id === 'pdf-extract' || id === 'pdf-organize') {
      const pages = await out.copyPages(docs[0], pageIndices(v.pages, docs[0].getPageCount()));
      for (const page of pages) { if (id === 'pdf-organize') page.setRotation(degrees((page.getRotation().angle + Number(v.rotation)) % 360)); out.addPage(page); }
    } else {
      let [pw, ph] = v.paper === 'a4' ? [595.276, 841.89] : [612, 792]; if (v.orientation === 'landscape') [pw, ph] = [ph, pw];
      for (const source of docs[0].getPages()) {
        const embedded = await out.embedPage(source), angle = ((source.getRotation().angle % 360) + 360) % 360;
        if (![0, 90, 180, 270].includes(angle)) throw new Error('PDF 页面旋转角度不受支持。');
        const rw = angle % 180 ? embedded.height : embedded.width, rh = angle % 180 ? embedded.width : embedded.height, scale = Math.min((pw - 36) / rw, (ph - 36) / rh), left = (pw - rw * scale) / 2, bottom = (ph - rh * scale) / 2;
        const x = left + (angle === 180 ? embedded.width * scale : angle === 270 ? embedded.height * scale : 0), y = bottom + (angle === 90 ? embedded.width * scale : angle === 180 ? embedded.height * scale : 0);
        out.addPage([pw, ph]).drawPage(embedded, { x, y, xScale: scale, yScale: scale, rotate: degrees(-angle) });
      }
    }
    return [await pdfFile(out)];
  } };
}