const fs = require('fs');
const path = require('path');
const converter = require('./src/util/templateConverter');

const convertDir = path.join(__dirname, 'flows-template/export');

if (!fs.existsSync(convertDir)) {
  console.error(`Directory not found: ${convertDir}`);
  process.exit(1);
}

console.log('==========================================');
console.log('开始转换模板 (Blaze -> Liquid + AMIS)');
console.log('==========================================');

const blazeFiles = fs.readdirSync(convertDir).filter(f => f.endsWith('.blaze'));
const fieldsCache = {}; // Cache fields.json content

blazeFiles.forEach(file => {
  const content = fs.readFileSync(path.join(convertDir, file), 'utf8');
  const flowId = file.split('.')[0];
  const isPrint = file.includes('print_template');

  // Load fields def
  let fields = fieldsCache[flowId];
  if (!fields) {
      const fieldsPath = path.join(convertDir, `${flowId}.fields.json`);
      if (fs.existsSync(fieldsPath)) {
          try {
            // Read fields as array
            fields = JSON.parse(fs.readFileSync(fieldsPath, 'utf8'));
            fieldsCache[flowId] = fields;
          } catch (e) {
              console.error(`Error parsing fields for ${flowId}:`, e.message);
          }
      }
  }

  try {
      const newContent = converter.convertTemplate(content, fields, isPrint);
      const newFile = file.replace('.blaze', '.liquid');
      fs.writeFileSync(path.join(convertDir, newFile), newContent);
      console.log(`✓ ${file} -> ${newFile}`);
  } catch (error) {
      console.error(`✗ Failed to convert ${file}:`, error.message);
  }
});

console.log('==========================================');
console.log('转换完成');
console.log('==========================================');
