#!/usr/bin/env node
/**
 * D44 家电保修台账构建脚本
 * 输入：../../inputs/spec.json（只读，不修改）
 * 输出：ledger.json / summary.csv / 每台 ICS / 合成凭证 / index.html
 *
 * 可重复执行：不写入当前时间戳，DTSTAMP 固定为基准日 00:00Z，
 * 因此相同输入每次生成的字节完全一致（自检会验证）。
 */
'use strict';

var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var DateCore = require('../date-core.js');

var OUT_DIR = path.resolve(__dirname, '..');
var ROOT_DIR = path.resolve(OUT_DIR, '..');
var SPEC_PATH = path.join(ROOT_DIR, 'inputs', 'spec.json');
var ICS_DIR = path.join(OUT_DIR, 'ics');
var DATA_DIR = path.join(OUT_DIR, 'data');
var RECEIPT_DIR = path.join(OUT_DIR, 'receipts');
var TEMPLATE_PATH = path.join(__dirname, 'page.template.html');

var WINDOW_DAYS = 30;
var CALENDAR_DOMAIN = 'cyberfete-d44.example';

function fail(message) {
  console.error('[build] 失败：' + message);
  process.exit(1);
}

function readJson(file) {
  var text;
  try {
    text = fs.readFileSync(file, 'utf8');
  } catch (error) {
    fail('无法读取 ' + file + '：' + error.message);
  }
  try {
    return JSON.parse(text);
  } catch (error) {
    fail('JSON 解析失败（' + file + '）：' + error.message);
  }
}

function trim(value) {
  return value === null || value === undefined ? '' : String(value).trim();
}

function isNonNegativeInteger(value) {
  return typeof value === 'number' && isFinite(value) && Math.floor(value) === value && value >= 0;
}

function validateSpec(spec) {
  var errors = [];
  if (!spec || typeof spec !== 'object') fail('spec 顶层必须是对象');
  if (!DateCore.isValidDate(spec.asOf)) {
    errors.push('asOf 无效：“' + spec.asOf + '”，应为真实存在的 YYYY-MM-DD 日期');
  }
  if (!Array.isArray(spec.items) || spec.items.length === 0) {
    errors.push('items 必须是非空数组');
  } else {
    var seen = Object.create(null);
    spec.items.forEach(function (item, index) {
      var label = 'items[' + index + ']';
      if (!item || typeof item !== 'object') {
        errors.push(label + ' 必须是对象');
        return;
      }
      var id = trim(item.id);
      var name = trim(item.name);
      if (!id) errors.push(label + ' 缺少 id');
      if (!name) errors.push(label + ' 缺少 name');
      if (id && seen[id]) errors.push('id 重复：' + id);
      if (id) seen[id] = true;
      if (!DateCore.isValidDate(item.purchaseDate)) {
        errors.push('【' + (id || label) + '】purchaseDate 无效：“' + item.purchaseDate + '”');
      }
      if (!isNonNegativeInteger(item.warrantyMonths)) {
        errors.push('【' + (id || label) + '】warrantyMonths 必须是非负整数：“' + item.warrantyMonths + '”');
      }
      var receipt = trim(item.receipt);
      if (!receipt) {
        errors.push('【' + (id || label) + '】receipt 文件名不能为空');
      } else if (path.basename(receipt) !== receipt || !/^[A-Za-z0-9._-]+\.txt$/.test(receipt) || receipt.indexOf('..') !== -1) {
        errors.push('【' + (id || label) + '】receipt 必须是安全的 .txt 文件名：“' + receipt + '”');
      }
    });
  }
  if (errors.length) fail('spec 校验未通过：\n  - ' + errors.join('\n  - '));
  return spec;
}

function noteFor(item, expiryDate, reminderDate) {
  if (item.id === 'A') {
    return '闰日购买：2024-02-29 加 24 个月，2026 年 2 月没有 29 日，按月末规则截止到 ' + expiryDate + '。';
  }
  if (item.id === 'B') {
    return '短保修期：2026-01-31 加 1 个月回退到 ' + expiryDate + '，保修不足 30 天，提醒日 ' + reminderDate + ' 早于购买日。';
  }
  return '常规保修：' + item.purchaseDate + ' 加 ' + item.warrantyMonths + ' 个月为 ' + expiryDate + '，日号保持不变。';
}

function buildLedger(spec) {
  var items = spec.items.map(function (item) {
    var purchaseDate = item.purchaseDate;
    var expiryDate = DateCore.warrantyEnd(purchaseDate, item.warrantyMonths);
    var reminderDate = DateCore.reminderDate(expiryDate, WINDOW_DAYS);
    var status = DateCore.statusOf(expiryDate, spec.asOf, WINDOW_DAYS);
    var id = trim(item.id);
    return {
      id: id,
      name: trim(item.name),
      purchaseDate: purchaseDate,
      warrantyMonths: item.warrantyMonths,
      expiryDate: expiryDate,
      reminderDate: reminderDate,
      status: status,
      daysText: DateCore.describeDays(expiryDate, spec.asOf, WINDOW_DAYS),
      receiptFile: trim(item.receipt),
      receiptPath: 'receipts/' + trim(item.receipt),
      icsFile: id + '-warranty.ics',
      icsPath: 'ics/' + id + '-warranty.ics',
      note: noteFor(item, expiryDate, reminderDate)
    };
  });

  var counts = { all: items.length, expiring: 0, active: 0, expired: 0 };
  items.forEach(function (item) {
    counts[item.status.code] += 1;
  });

  return {
    meta: {
      title: '家电保修台账',
      asOf: spec.asOf,
      windowDays: WINDOW_DAYS,
      generatedBy: 'outputs/src/build.js',
      rule: '购买日加保修月数；目标月无同日则取月末；保修截至截止日当天结束；提前 30 天全天提醒。',
      disclaimer: '全部为合成练习数据；凭证是脚本生成的纯文字副本，不是真实票据，不可用于报销、售后或任何真实场景。',
      counts: counts
    },
    items: items
  };
}

function syntheticCode(item) {
  return crypto.createHash('sha256')
    .update([item.id, item.name, item.purchaseDate, item.warrantyMonths].join('|'), 'utf8')
    .digest('hex')
    .slice(0, 12)
    .toUpperCase();
}

/** 终端显示宽度：CJK 与全角符号按 2 列计算，用于纯文本凭证对齐。 */
function displayWidth(text) {
  var width = 0;
  Array.from(String(text)).forEach(function (ch) {
    var code = ch.codePointAt(0);
    var wide = (code >= 0x1100 && code <= 0x115f) ||
      (code >= 0x2e80 && code <= 0xa4cf) ||
      (code >= 0xac00 && code <= 0xd7a3) ||
      (code >= 0xf900 && code <= 0xfaff) ||
      (code >= 0xfe30 && code <= 0xfe6f) ||
      (code >= 0xff00 && code <= 0xff60) ||
      (code >= 0xffe0 && code <= 0xffe6) ||
      (code >= 0x20000 && code <= 0x3fffd);
    width += wide ? 2 : 1;
  });
  return width;
}

function padLabel(label, width) {
  var spaces = width - displayWidth(label);
  return label + (spaces > 0 ? ' '.repeat(spaces) : '');
}

function receiptText(item, spec, ledgerItem) {
  var line = '='.repeat(68);
  var thin = '-'.repeat(68);
  var amount = { A: '199.00', B: '329.00', C: '459.00' }[item.id] || '0.00';
  var code = syntheticCode(item);
  var rows = [
    ['练习编号', ledgerItem.id],
    ['家电名称', ledgerItem.name],
    ['购买日期', ledgerItem.purchaseDate],
    ['保修月数', ledgerItem.warrantyMonths + ' 个月'],
    ['保修截止日', ledgerItem.expiryDate + '（当天结束）'],
    ['提前提醒日', ledgerItem.reminderDate + '（提前 ' + WINDOW_DAYS + ' 天）'],
    ['凭证代号', 'SYN-D44-' + ledgerItem.id + '-' + ledgerItem.purchaseDate.replace(/-/g, '')],
    ['合成校验码', code],
    ['销售方（虚构）', '赛博游园会合成数据工坊'],
    ['金额（虚构）', '¥' + amount],
    ['本地文件', 'receipts/' + ledgerItem.receiptFile]
  ];
  var padWidth = 16;
  var body = rows.map(function (pair) {
    return '  ' + padLabel(pair[0], padWidth) + '：' + pair[1];
  });

  return [
    line,
    '   【合成练习凭证 · 非真实票据】   SYNTHETIC / D44',
    line,
    '',
    '  本文件由赛博游园会 D44 练习脚本自动生成，仅用于“家电保修台账”',
    '  演示。它不是真实发票、收据、保修卡或付款记录，不具备任何法律、',
    '  财务、报销或售后效力。文中的商家、金额、编号、日期均为虚构。',
    '',
    thin,
    ''
  ].concat(body.concat([
    '',
    thin,
    '  备注',
    '  ' + ledgerItem.note,
    '',
    '  状态（基准日 ' + spec.asOf + '）',
    '  ' + ledgerItem.status.label + '，' + ledgerItem.daysText + '。',
    '',
    thin,
    '',
    '  【合成标记】SYNTHETIC-D44-' + ledgerItem.id + ' / ' + code,
    '  生成基准日 ' + spec.asOf + '（由 outputs/src/build.js 生成）',
    '  再次声明：本凭证为合成练习材料，不是真实票据，请勿用于任何',
    '  真实交易、报销或保修申请。',
    line,
    ''
  ])).join('\n');
}

function escapeIcsText(text) {
  return String(text)
    .replace(/\\/g, '\\\\')
    .replace(/;/g, '\\;')
    .replace(/,/g, '\\,')
    .replace(/\r\n|\r|\n/g, '\\n');
}

/** 强制按字节折行，避免切断 UTF-8 字符或行尾转义反斜杠。 */
function hardFold(text, limit) {
  var chunks = [];
  var current = '';
  var currentBytes = 0;
  Array.from(text).forEach(function (ch) {
    var size = Buffer.byteLength(ch, 'utf8');
    if (currentBytes + size > limit) {
      var carry = '';
      while (current.slice(-1) === '\\') {
        carry = '\\' + carry;
        current = current.slice(0, -1);
        currentBytes -= 1;
      }
      chunks.push(current);
      current = carry + ch;
      currentBytes = carry.length + size;
    } else {
      current += ch;
      currentBytes += size;
    }
  });
  if (current) chunks.push(current);
  return chunks;
}

/**
 * RFC 5545 折行：优先在空格处折行，避免拆散日期；
 * 每行不超过 75 个八位组（续行含一个前导空格），且不切断 UTF-8 字符或转义序列。
 */
function foldIcsLine(line) {
  var tokens = String(line).match(/\s+|\S+/g) || [];
  var lines = [];
  var current = '';

  function currentBytes() {
    return Buffer.byteLength(current, 'utf8');
  }

  tokens.forEach(function (token) {
    var limit = lines.length === 0 ? 75 : 74;
    if (currentBytes() + Buffer.byteLength(token, 'utf8') <= limit) {
      current += token;
      return;
    }
    if (current) {
      lines.push(current);
      current = '';
    }
    var rest = token.replace(/^\s+/, '');
    if (!rest) return;
    limit = lines.length === 0 ? 75 : 74;
    if (Buffer.byteLength(rest, 'utf8') <= limit) {
      current = rest;
      return;
    }
    var chunks = hardFold(rest, limit);
    chunks.forEach(function (chunk, index) {
      if (index < chunks.length - 1) lines.push(chunk);
      else current = chunk;
    });
  });

  if (current) lines.push(current);
  if (!lines.length) lines.push('');
  return lines.join('\r\n ');
}

function icsDate(dateText) {
  return dateText.replace(/-/g, '');
}

function icsEvent(lines) {
  return ['BEGIN:VEVENT'].concat(lines, ['END:VEVENT']);
}

function icsText(ledgerItem, spec) {
  var item = ledgerItem;
  var stamp = spec.asOf.replace(/-/g, '') + 'T000000Z';
  var statusText = item.status.label + '，' + item.daysText;
  var baseDescription = [
    '合成练习数据，非真实票据。',
    '家电：' + item.name + '（' + item.id + '）',
    '购买日：' + item.purchaseDate,
    '保修月数：' + item.warrantyMonths + ' 个月',
    '保修截止日：' + item.expiryDate + '（当天结束）',
    '提前提醒日：' + item.reminderDate + '（提前 ' + WINDOW_DAYS + ' 天）',
    '状态（基准 ' + spec.asOf + '）：' + statusText,
    '凭证：' + item.receiptPath
  ].join('\n');

  var lines = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//CyberFete D44//Warranty Ledger//ZH-CN',
    'CALSCALE:GREGORIAN',
    'METHOD:PUBLISH',
    'X-WR-CALNAME:' + escapeIcsText('家电保修提醒 · ' + item.name + '（' + item.id + '）'),
    'X-WR-TIMEZONE:Asia/Shanghai',
    'X-D44-DISCLAIMER:' + escapeIcsText('合成练习数据；不是真实票据'),
    'X-D44-AS-OF:' + icsDate(spec.asOf)
  ];

  lines = lines.concat(icsEvent([
    'UID:d44-warranty-' + item.id + '-start@' + CALENDAR_DOMAIN,
    'DTSTAMP:' + stamp,
    'DTSTART;VALUE=DATE:' + icsDate(item.purchaseDate),
    'DTEND;VALUE=DATE:' + icsDate(DateCore.addDays(item.purchaseDate, 1)),
    'SUMMARY:' + escapeIcsText('保修开始 · ' + item.name + '（' + item.id + '）'),
    'DESCRIPTION:' + escapeIcsText(baseDescription),
    'CATEGORIES:' + escapeIcsText('合成练习') + ',' + escapeIcsText('家电保修'),
    'STATUS:CONFIRMED',
    'TRANSP:TRANSPARENT',
    'X-D44-ITEM-ID:' + item.id,
    'X-D44-EVENT-KIND:start'
  ]));

  lines = lines.concat(icsEvent([
    'UID:d44-warranty-' + item.id + '-remind@' + CALENDAR_DOMAIN,
    'DTSTAMP:' + stamp,
    'DTSTART;VALUE=DATE:' + icsDate(item.reminderDate),
    'DTEND;VALUE=DATE:' + icsDate(DateCore.addDays(item.reminderDate, 1)),
    'SUMMARY:' + escapeIcsText('提前 30 天提醒 · ' + item.name + '（' + item.id + '）'),
    'DESCRIPTION:' + escapeIcsText('合成练习提醒：' + item.name + '（' + item.id + '）将于 ' + item.expiryDate + ' 保修截止。\n' + baseDescription),
    'CATEGORIES:' + escapeIcsText('合成练习') + ',' + escapeIcsText('保修提醒'),
    'STATUS:CONFIRMED',
    'TRANSP:TRANSPARENT',
    'X-D44-ITEM-ID:' + item.id,
    'X-D44-EVENT-KIND:remind'
  ]));

  lines = lines.concat(icsEvent([
    'UID:d44-warranty-' + item.id + '-expiry@' + CALENDAR_DOMAIN,
    'DTSTAMP:' + stamp,
    'DTSTART;VALUE=DATE:' + icsDate(item.expiryDate),
    'DTEND;VALUE=DATE:' + icsDate(DateCore.addDays(item.expiryDate, 1)),
    'SUMMARY:' + escapeIcsText('保修截止 · ' + item.name + '（' + item.id + '）'),
    'DESCRIPTION:' + escapeIcsText(baseDescription),
    'CATEGORIES:' + escapeIcsText('合成练习') + ',' + escapeIcsText('保修截止'),
    'STATUS:CONFIRMED',
    'TRANSP:TRANSPARENT',
    'X-D44-ITEM-ID:' + item.id,
    'X-D44-EVENT-KIND:expiry',
    'BEGIN:VALARM',
    'ACTION:DISPLAY',
    'DESCRIPTION:' + escapeIcsText('提前 30 天提醒：' + item.name + '（' + item.id + '）将于 ' + item.expiryDate + ' 保修截止（合成练习）'),
    'TRIGGER:-P30D',
    'END:VALARM'
  ]));

  lines.push('END:VCALENDAR');
  return lines.map(foldIcsLine).join('\r\n') + '\r\n';
}

function csvField(value) {
  var text = value === null || value === undefined ? '' : String(value);
  if (/[",\r\n]/.test(text)) {
    return '"' + text.replace(/"/g, '""') + '"';
  }
  return text;
}

function csvText(ledger) {
  var header = [
    '序号', '编号', '家电名称', '购买日期', '保修月数', '保修截止日', '提前30天提醒日',
    '基准日', '截止状态', '剩余天数', '逾期天数', '状态说明', '凭证文件', '凭证本地路径',
    'ICS文件', '备注'
  ];
  var rows = ledger.items.map(function (item, index) {
    return [
      index + 1,
      item.id,
      item.name,
      item.purchaseDate,
      item.warrantyMonths,
      item.expiryDate,
      item.reminderDate,
      ledger.meta.asOf,
      item.status.label,
      item.status.daysRemaining,
      item.status.overdueDays,
      item.daysText,
      item.receiptFile,
      item.receiptPath,
      item.icsPath,
      item.note
    ];
  });
  var lines = [header].concat(rows).map(function (row) {
    return row.map(csvField).join(',');
  });
  return '\ufeff' + lines.join('\r\n') + '\r\n';
}

function safeJsonForScript(value) {
  return JSON.stringify(value)
    .replace(/</g, '\\u003c')
    .replace(/>/g, '\\u003e')
    .replace(/&/g, '\\u0026')
    .replace(/\u2028/g, '\\u2028')
    .replace(/\u2029/g, '\\u2029');
}

function buildHtml(ledger) {
  var template = fs.readFileSync(TEMPLATE_PATH, 'utf8');
  if (template.indexOf('__LEDGER_JSON__') === -1) {
    fail('页面模板缺少 __LEDGER_JSON__ 占位符');
  }
  return template.replace('__LEDGER_JSON__', safeJsonForScript(ledger));
}

function writeFile(file, content) {
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, content, 'utf8');
  console.log('[build] 写入 ' + path.relative(ROOT_DIR, file) + '（' + Buffer.byteLength(content, 'utf8') + ' 字节）');
}

function main() {
  var spec = validateSpec(readJson(SPEC_PATH));
  var ledger = buildLedger(spec);

  console.log('[build] 输入 ' + path.relative(ROOT_DIR, SPEC_PATH) + '，基准日 ' + spec.asOf);
  ledger.items.forEach(function (item) {
    console.log('[build] ' + item.id + ' ' + item.name + '：' + item.purchaseDate + ' + ' +
      item.warrantyMonths + ' 个月 → ' + item.expiryDate + '（' + item.status.label + '，' + item.daysText + '）');
    writeFile(path.join(RECEIPT_DIR, item.receiptFile), receiptText(
      spec.items.filter(function (raw) { return trim(raw.id) === item.id; })[0], spec, item
    ));
    writeFile(path.join(ICS_DIR, item.icsFile), icsText(item, spec));
  });

  writeFile(path.join(DATA_DIR, 'ledger.json'), JSON.stringify(ledger, null, 2) + '\n');
  writeFile(path.join(DATA_DIR, 'summary.csv'), csvText(ledger));
  writeFile(path.join(OUT_DIR, 'index.html'), buildHtml(ledger));
  console.log('[build] 完成：' + ledger.items.length + ' 台家电');
}

try {
  main();
} catch (error) {
  fail(error && error.stack ? error.stack : String(error));
}