#!/usr/bin/env node
/**
 * build-csv.js — 由 inputs/spec.json 生成 outputs/scenarios.csv
 * ---------------------------------------------------------------------------
 * 用法：
 *   node build-csv.js            # 使用默认路径 ../inputs/spec.json -> ./scenarios.csv
 *   node build-csv.js <spec.json> <out.csv>
 *
 * 说明：
 *   - inputs/spec.json 只读，本脚本仅读取它。
 *   - 复用 energy-core.js 中的纯函数，保证 CSV 与页面结果口径一致。
 *   - 输出带 UTF-8 BOM，方便 Excel 直接打开中文不乱码。
 */
'use strict';

var fs = require('fs');
var path = require('path');
var core = require('./energy-core.js');

var defaultSpec = path.resolve(__dirname, '..', 'inputs', 'spec.json');
var defaultOut = path.resolve(__dirname, 'scenarios.csv');

var specPath = process.argv[2] ? path.resolve(process.argv[2]) : defaultSpec;
var outPath = process.argv[3] ? path.resolve(process.argv[3]) : defaultOut;

var spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));

var params = {
  fixtures: spec.fixtures,
  beforeWatts: spec.beforeWatts,
  afterWatts: spec.afterWatts,
  daysPerYear: spec.daysPerYear,
  priceCnyPerKwh: spec.priceCnyPerKwh,
  investmentCny: spec.investmentCny,
  scenarioHours: spec.scenarioHours,
  maintenanceDifferenceCnyPerYear: spec.maintenanceDifferenceCnyPerYear,
  note: spec.note
};

var computed = core.computeAll(params);
var csv = core.buildCSV(params, computed);

fs.writeFileSync(outPath, '﻿' + csv, 'utf8');

process.stdout.write('spec : ' + specPath + '\n');
process.stdout.write('out  : ' + outPath + '\n');
computed.scenarios.forEach(function (sc) {
  if (!sc.ok) {
    process.stdout.write('  - ' + sc.label + ' (第' + sc.slot + '档): 输入非法，未计算 — ' +
      (sc.errors[0] ? sc.errors[0].message : '') + '\n');
    return;
  }
  var r = sc.result;
  process.stdout.write(
    '  - ' + sc.label + ' (第' + sc.slot + '档, ' + sc.hours + ' h/d): ' +
    '年耗电 ' + core.formatKWh(r.beforeKwh) + ' -> ' + core.formatKWh(r.afterKwh) + ' kWh, ' +
    '年电费 ' + core.formatCNY(r.costBefore) + ' -> ' + core.formatCNY(r.costAfter) + ', ' +
    '节电额 ' + core.formatCNY(r.grossSaving) + ', 维护费差额 ' + core.formatCNY(r.maintenanceDelta) + ', ' +
    '净收益 ' + core.formatCNY(r.netSaving) + ', 回收期 ' + core.formatPayback(r.paybackYears) +
    ' [' + (r.rankLabel || '') + ']\n'
  );
});
if (computed.globalErrors.length) {
  computed.globalErrors.forEach(function (e) { process.stdout.write('  ! ' + e.message + '\n'); });
}
process.stdout.write('已写出 ' + outPath + '（' + csv.split('\r\n').length + ' 行）\n');
