#!/usr/bin/env node
/**
 * 修复 ArkTS 兼容性问题的脚本
 * 主要修复:
 * 1. Map 解构赋值 (for...of)
 * 2. this 返回类型
 * 3. 对象索引访问
 * 4. Partial<T> 类型
 * 5. 构造签名
 */

const fs = require('fs');
const path = require('path');

const runtimeDir = './runtime/arkpb';

function fixFile(filePath) {
  console.log(`Processing: ${filePath}`);
  let content = fs.readFileSync(filePath, 'utf-8');
  let changes = 0;

  // 1. 修复 Map 解构赋值: for (const [k, v] of map)
  const forOfPattern = /for\s*\(\s*const\s*\[\s*(\w+)\s*,\s*(\w+)\s*\]\s*of\s*(\w+)\s*\)/g;
  const beforeForOf = content;
  content = content.replace(forOfPattern, (match, k, v, mapName) => {
    changes++;
    return `${mapName}.forEach((${v}, ${k}) => `;
  });

  // 如果替换了 for...of,需要添加对应的右括号
  if (content !== beforeForOf) {
    // 找到被替换的 for 循环的结束位置并添加 })
    content = content.replace(/for\s+\(/g, 'for (');  // 占位,实际需要更精确的处理
  }

  // 2. 修复 this 返回类型: ): this {
  const thisReturnPattern = /\):\s*this\s*{/g;
  const beforeThis = content;
  content = content.replace(thisReturnPattern, () => {
    changes++;
    return '): Message {';  // 或者删除类型注解: ') {'
  });

  // 3. 修复 Partial<T>: 替换为自定义类型或可选参数
  const partialPattern = /Partial<(\w+)>/g;
  const beforePartial = content;
  content = content.replace(partialPattern, (match, typeName) => {
    changes++;
    return `${typeName}Init`;  // 使用 Init 接口
  });

  // 4. 修复构造签名: new(): Message
  if (content.includes('new(): Message')) {
    changes++;
    content = content.replace(/new\(\):\s*Message/g, 'create(): Message');
  }

  if (changes > 0) {
    console.log(`  ✅ Fixed ${changes} issues`);
    fs.writeFileSync(filePath, content);
  } else {
    console.log(`  ⏭️  No changes needed`);
  }

  return changes;
}

function processDirectory(dir) {
  const files = fs.readdirSync(dir);
  let totalChanges = 0;

  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      totalChanges += processDirectory(filePath);
    } else if (file.endsWith('.ets')) {
      totalChanges += fixFile(filePath);
    }
  }

  return totalChanges;
}

console.log('🔧 Starting ArkTS compatibility fixes...\n');
const totalChanges = processDirectory(runtimeDir);
console.log(`\n✅ Done! Fixed ${totalChanges} issues total.`);