const fs = require('fs');
// 读取 SQL 文件内容
const sql = fs.readFileSync('example.sql', 'utf8');

function parseSql(sql) {
  const tables = {};

  // 匹配DROP TABLE语句
  const dropTableRegex = /DROP\s+TABLE\s+`(\w+)`\s*;/gi;
  let dropMatch = null;
  while ((dropMatch = dropTableRegex.exec(sql)) !== null) {
    const tableName = dropMatch[1];
    delete tables[tableName]; // 从表对象中删除该表
  }

  // 匹配CREATE TABLE语句
  const createTableRegex = /CREATE\s+TABLE\s+`(\w+)`\s*\(([\s\S]*?)\)(.*?);/gi;
  let match = null;
  while ((match = createTableRegex.exec(sql)) !== null) {
    const tableName = match[1];
    const fieldDefs = match[2];

    // 新建表的对象
    tables[tableName] = {
      mode: 'simple',
      modelCn: tableName,
      fields: {}, // 将字段定义改为对象
      foreign: {},
      extendActions: {},
      primaryKey: '',
      middlewares: ['loginRequired']
    };

    // 匹配字段定义
    const fieldRegex = /`(\w+)`\s+(int|varchar|char|text|date|datetime)\s*(?:\((.*?)\))?\s*(unsigned)?\s*(?:NOT NULL)?\s*(?:default\s+(?:NULL|'[^']*'))?\s*(?:COMMENT\s+'(.*?)')?(?:\s+PRIMARY KEY)?/gi;    let fieldMatch = null;
    while ((fieldMatch = fieldRegex.exec(fieldDefs)) !== null) {
      const fieldName = fieldMatch[1];
      let fieldType = fieldMatch[2];
      const fieldLength = fieldMatch[3];
      const isUnsigned = fieldMatch[4];
      const defaultValue = fieldMatch[5];
      const comment = fieldMatch[6] || fieldMatch[7];

     

      // 将字段类型转换为统一的类型
      switch (fieldType) {
        case 'int':
          fieldType = 'integer';
          break;
        case 'varchar':
        case 'char':
        case 'text':
          fieldType = 'string';
          break;
        case 'date':
        case 'datetime':
          fieldType = 'date';
          break;
      }

      // 将字段添加到表对象中，并添加注释到meta.comment属性中
      tables[tableName].fields[fieldName] = {
        type: fieldType,
        length: fieldLength,
        unsigned: isUnsigned,
        default: defaultValue,
        meta: {
          comment: comment // 将字段注释添加到meta.comment属性中
        }
      };

      // 如果该字段是主键，则将其名称添加到primaryKey属性中
      if (fieldMatch[0].includes('PRIMARY KEY')) {
        tables[tableName].primaryKey = fieldName;
      }
    }
  }

  return tables;
}



  
    // // 将每一个结果输出成 js文件
    // for (const tableName in tables) {
    //         const table = tables[tableName];
    //         const filename = `${tableName}.js`;
    //         const content = `module.exports = ${JSON.stringify(table, null, 2)};`;

    //         // 写入文件
    //         //   const fileContent = `module.exports = ${JSON.stringify(tables[tableName], null, 2)};\n`;
    //         fs.writeFileSync(filename, content);
    //     }
    //     return tables;
    // }

    // 输出结果
    parseSql(sql)
// console.log("    parseSql(sql)",parseSql(sql))