/**
 * Office tool fidelity bench — generate one rich sample per family
 * (.docx, .xlsx, .pptx) into ./bench-out so the team can open them
 * in real Word / Excel / PowerPoint and verify rendering fidelity.
 *
 * Run:
 *   node scripts/office-bench/generate-samples.mjs
 *
 * Output:
 *   bench-out/office/sample.docx
 *   bench-out/office/sample.xlsx
 *   bench-out/office/sample.pptx
 */

import path from 'path';
import { fileURLToPath } from 'url';
import { mkdir } from 'fs/promises';

import OfficeTool from '../../src/tools/officeTool.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(__dirname, '..', '..');
const outDir = path.join(projectRoot, 'bench-out', 'office');

await mkdir(outDir, { recursive: true });

const tool = new OfficeTool({}, { info() {}, warn() {}, error() {}, debug() {} });
const ctx = { projectDir: projectRoot, agentId: 'bench' };

const docSpec = {
  title: 'Office Bench — Word Fidelity Sample',
  author: 'Loxia Bench',
  pageSize: 'letter',
  sections: [{
    children: [
      { type: 'heading', level: 1, text: 'Word — Rich Features Showcase' },
      { type: 'paragraph', text: 'This document exercises every feature of the office.doc.create surface so the team can verify rendering fidelity in Microsoft Word, Google Docs, and LibreOffice.' },

      { type: 'heading', level: 2, text: 'Lists' },
      { type: 'list', items: ['Bullet one', 'Bullet two', { text: 'Nested', level: 1 }, { text: 'Deeper', level: 2 }] },
      { type: 'list', ordered: true, items: ['First', 'Second', 'Third'] },

      { type: 'heading', level: 2, text: 'Tables' },
      { type: 'table',
        headers: ['Region', 'Q1', 'Q2', 'Q3'],
        rows: [
          ['East',  '1,200', '1,310', '1,420'],
          ['West',  '980',   '1,120', '1,150'],
          ['North', '1,430', '1,500', '1,600'],
        ],
        headerFill: '#1F3864',
        alternateFill: '#F2F6FC',
      },

      { type: 'heading', level: 2, text: 'Callouts' },
      { type: 'callout', label: 'Rule of thumb', content: 'Every batch operation uses the same plural-canonical envelope.', color: '#2E75B6' },
      { type: 'callout', label: 'Warning', content: 'Do not bypass the catalog.', color: '#C00000' },

      { type: 'heading', level: 2, text: 'Hyperlinks' },
      { type: 'hyperlink', text: 'Anthropic', url: 'https://www.anthropic.com' },

      { type: 'pageBreak' },
      { type: 'heading', level: 1, text: 'Page Two' },
      { type: 'paragraph', text: 'Page break worked.' },
      { type: 'horizontalRule' },
      { type: 'richParagraph', runs: [
        { text: 'Mixed runs: ', bold: true },
        { text: 'italic ', italic: true },
        { text: 'colored ', color: '#2E75B6' },
        { text: 'Consolas ', font: 'Consolas' },
        { text: 'size 14pt.', size: 14 },
      ]},
    ],
  }],
};

const sheetSpec = {
  creator: 'Loxia Bench',
  properties: { title: 'Office Bench — Excel Fidelity Sample', company: 'Loxia' },
  sheets: [
    {
      name: 'Sales',
      tabColor: '#1F3864',
      columns: [
        { header: 'Region', key: 'region',  width: 16 },
        { header: 'Q1',     key: 'q1',      width: 12, type: 'currency' },
        { header: 'Q2',     key: 'q2',      width: 12, type: 'currency' },
        { header: 'Q3',     key: 'q3',      width: 12, type: 'currency' },
        { header: 'Total',  key: 'total',   width: 14, type: 'currency' },
      ],
      headerStyle: { bold: true, fontColor: '#FFFFFF', fill: '#1F3864', height: 22 },
      alternateRowFill: '#F2F6FC',
      rows: [
        { region: 'East',  q1: 1200, q2: 1310, q3: 1420, total: '=SUM(B2:D2)' },
        { region: 'West',  q1: 980,  q2: 1120, q3: 1150, total: '=SUM(B3:D3)' },
        { region: 'North', q1: 1430, q2: 1500, q3: 1600, total: '=SUM(B4:D4)' },
      ],
      freezeRow: 1,
      autoFilter: true,
      cellStyles: [
        { cell: 'E2', bold: true },
        { cell: 'E3', bold: true },
        { cell: 'E4', bold: true },
      ],
      mergedCells: [],
      conditionalFormatting: [
        { range: 'B2:D4', type: 'colorScale', min: '#F8696B', mid: '#FFEB84', max: '#63BE7B' },
      ],
      namedRanges: [{ name: 'Q1Totals', range: 'B2:B4' }],
    },
    {
      name: 'Pivot Notes',
      columns: [{ header: 'Note', key: 'note', width: 80 }],
      rows: [
        { note: 'Color scale shows hot/cold quarters across regions.' },
        { note: 'Sales!E2:E4 are SUM formulas — touch a value and watch them recompute.' },
      ],
      headerStyle: { bold: true, fontColor: '#FFFFFF', fill: '#2E75B6' },
    },
  ],
};

const presSpec = {
  title: 'Office Bench — PowerPoint Fidelity Sample',
  author: 'Loxia Bench',
  company: 'Loxia',
  layout: '16:9',
  theme: { primaryColor: '#1F3864', accentColor: '#2E75B6', fontFamily: 'Calibri' },
  slides: [
    { layout: 'title', title: 'Office Bench', subtitle: 'PowerPoint fidelity sample' },
    { layout: 'section-header', title: 'Section: Features' },
    { layout: 'content', title: 'Bullets', content: [
      { type: 'bullets', items: ['First point', 'Second point', { text: 'Nested', level: 1, ordered: false }, 'Third'], x: 0.5, y: 1.5, w: 9, h: 4 },
    ], notes: 'Speaker notes — this is the bullets slide.' },
    { layout: 'content', title: 'Table', content: [
      { type: 'table',
        headers: ['Region', 'Q1', 'Q2'],
        rows: [['East', '1200', '1310'], ['West', '980', '1120'], ['North', '1430', '1500']],
        x: 0.5, y: 1.5, w: 9, h: 2.5,
        headerStyle: { fill: '#1F3864', color: '#FFFFFF' },
      },
    ]},
    { layout: 'content', title: 'Shapes', content: [
      { type: 'shape', shape: 'rect',     x: 0.5, y: 1.5, w: 2, h: 1.5, fill: '#1F3864' },
      { type: 'shape', shape: 'rounded',  x: 2.8, y: 1.5, w: 2, h: 1.5, fill: '#2E75B6' },
      { type: 'shape', shape: 'ellipse',  x: 5.1, y: 1.5, w: 2, h: 1.5, fill: '#5B9BD5' },
      { type: 'text', text: 'Shapes — fills + borders work.', x: 0.5, y: 3.5, w: 9, h: 0.5, fontSize: 14, color: '#595959' },
    ]},
    { layout: 'content', title: 'Chart', content: [
      { type: 'chart', chartType: 'bar', title: 'Quarterly Sales', x: 0.5, y: 1.5, w: 9, h: 4.5,
        data: [
          { name: 'Q1', labels: ['East', 'West', 'North'], values: [1200, 980, 1430] },
          { name: 'Q2', labels: ['East', 'West', 'North'], values: [1310, 1120, 1500] },
        ],
      },
    ]},
  ],
};

async function emit(action, spec, name) {
  const out = path.join(outDir, name);
  const r = await tool.execute({
    actions: [{ type: action, outputPath: out, content: spec }],
  }, ctx);
  if (!r.success) {
    console.error(`✗ ${action} failed: ${r.error || r.output}`);
    process.exit(1);
  }
  console.log(`✓ ${action}  →  ${r.outputPath}  (${(r.fileSize / 1024).toFixed(1)} KB)`);
  return r;
}

await emit('doc.create',   docSpec,   'sample.docx');
await emit('sheet.create', sheetSpec, 'sample.xlsx');
await emit('pres.create',  presSpec,  'sample.pptx');

console.log(`\nOpen the three files in real Office apps and verify:`);
console.log(`  - sample.docx: heading colors, list nesting, table zebra, callout left bar, page break, hyperlink`);
console.log(`  - sample.xlsx: header bar, currency formatting, SUM formulas, color-scale conditional formatting, frozen row 1, autofilter`);
console.log(`  - sample.pptx: title slide, bullets, table, shapes (rect/rounded/ellipse with fills), bar chart with two series`);
