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

// 获取数据库文件路径
const getDbPath = () => {
  let basePath;
  if (process.platform === 'darwin') {
    // macOS
    basePath = path.join(os.homedir(), 'Library/Application Support/lip_sync');
  } else if (process.platform === 'win32') {
    // Windows
    basePath = path.join(os.homedir(), 'AppData/Roaming/lip_sync');
  } else {
    // Linux
    basePath = path.join(os.homedir(), '.local/share/lip_sync');
  }
  
  // 确保目录存在
  if (!fs.existsSync(basePath)) {
    fs.mkdirSync(basePath, { recursive: true });
  }
  
  return path.join(basePath, 'lip_sync.db');
};

// 创建Knex实例
const db = knex({
  client: 'sqlite3',
  connection: {
    filename: getDbPath(),
  },
  useNullAsDefault: true, // SQLite需要此选项
  pool: {
    afterCreate: (conn, cb) => {
      // 启用外键约束
      conn.run('PRAGMA foreign_keys = ON', cb);
    }
  }
});

// 初始化数据库
const initDB = async () => {
  // 创建book表
  const hasBookTable = await db.schema.hasTable('book');
  if (!hasBookTable) {
    await db.schema.createTable('book', (table) => {
      table.increments('id').primary();
      table.string('title').notNullable();
      table.string('video_path').nullable();
      table.string('subtitle_path').nullable();
      table.string('audio_path').nullable(); // 添加音频文件路径字段
      table.timestamp('created_at').defaultTo(db.fn.now());
      table.timestamp('updated_at').defaultTo(db.fn.now());
    });
    console.log('创建book表成功');
  } else {
    // 检查表是否需要更新字段
    const columns = await db.table('book').columnInfo();
    
    // 添加新字段（如果不存在）
    if (!columns.audio_path) {
      await db.schema.table('book', table => {
        table.string('audio_path').nullable();
      });
      console.log('更新book表结构：添加audio_path字段');
    }
  }
  
  // 创建book_info表
  const hasBookInfoTable = await db.schema.hasTable('book_info');
  if (!hasBookInfoTable) {
    await db.schema.createTable('book_info', (table) => {
      table.increments('id').primary();
      table.integer('book_id').unsigned().notNullable();
      table.text('subtitle_content').nullable();
      table.text('subtitle_segments').nullable();
      table.string('audio_path').nullable(); // 音频文件路径
      table.string('image_path').nullable(); // 图片文件路径
      table.text('description').nullable(); // 描述词
      table.string('video_path').nullable(); // 口播视频路径
      table.boolean('is_merged').defaultTo(false); // 是否已合并
      table.integer('merged_from').nullable(); // 从哪些分镜合并而来，存储分镜ID数组的JSON字符串
      table.timestamp('created_at').defaultTo(db.fn.now());
      table.timestamp('updated_at').defaultTo(db.fn.now());
      
      // 外键约束，删除book时级联删除book_info
      table.foreign('book_id').references('id').inTable('book').onDelete('CASCADE');
      
      // 索引
      table.unique(['book_id']);
    });
    console.log('创建book_info表成功');
  } else {
    // 检查表是否需要更新字段
    const columns = await db.table('book_info').columnInfo();
    
    // 添加新字段（如果不存在）
    const updates = [];
    if (!columns.audio_path) {
      updates.push(db.schema.table('book_info', table => {
        table.string('audio_path').nullable();
      }));
    }
    if (!columns.image_path) {
      updates.push(db.schema.table('book_info', table => {
        table.string('image_path').nullable();
      }));
    }
    if (!columns.description) {
      updates.push(db.schema.table('book_info', table => {
        table.text('description').nullable();
      }));
    }
    if (!columns.video_path) {
      updates.push(db.schema.table('book_info', table => {
        table.string('video_path').nullable();
      }));
    }
    if (!columns.is_merged) {
      updates.push(db.schema.table('book_info', table => {
        table.boolean('is_merged').defaultTo(false);
      }));
    }
    if (!columns.merged_from) {
      updates.push(db.schema.table('book_info', table => {
        table.integer('merged_from').nullable();
      }));
    }
    
    if (updates.length > 0) {
      await Promise.all(updates);
      console.log('更新book_info表成功');
    }
  }
  
  return db;
};

module.exports = {
  db,
  initDB,
  getDbPath
}; 