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 updateDbStructure = async (db) => {
  // 检查book表是否有style字段
  const hasStyleColumn = await db.schema.hasColumn('book', 'style');
  if (!hasStyleColumn) {
    console.log('添加style字段到book表');
    await db.schema.table('book', table => {
      table.string('style').nullable();
    });
  }

  // 检查book_info表是否有image_path字段
  const hasImagePathColumn = await db.schema.hasColumn('book_info', 'image_path');
  if (!hasImagePathColumn) {
    console.log('添加image_path字段到book_info表');
    await db.schema.table('book_info', table => {
      table.string('image_path').nullable();
    });
  }

  // 检查book_info表是否有description字段
  const hasDescriptionColumn = await db.schema.hasColumn('book_info', 'description');
  if (!hasDescriptionColumn) {
    console.log('添加description字段到book_info表');
    await db.schema.table('book_info', table => {
      table.text('description').nullable();
    });
  }

  // 检查book_info表是否有draw_status字段
  const hasDrawStatusColumn = await db.schema.hasColumn('book_info', 'draw_status');
  if (!hasDrawStatusColumn) {
    console.log('添加draw_status字段到book_info表');
    await db.schema.table('book_info', table => {
      table.integer('draw_status').defaultTo(2); // 默认为2(完成)，对于已有的项目不需要重新绘制
    });
  }
};

// 初始化数据库
const initDatabase = async (forceUpdate = false) => {
  console.log(`开始初始化数据库，forceUpdate=${forceUpdate}`);
  try {
    // 获取数据库路径
    const dbPath = await getDbPath();
    
    // 确保数据库目录存在
    const dbDir = path.dirname(dbPath);
    if (!fs.existsSync(dbDir)) {
      fs.mkdirSync(dbDir, { recursive: true });
    }
    
    console.log(`初始化数据库，路径: ${dbPath}`);
    
    // 创建数据库连接
    const db = knex({
      client: 'sqlite3',
      connection: {
        filename: dbPath,
      },
      useNullAsDefault: true,
    });
    
    // 如果数据库已存在但需要强制更新
    if (forceUpdate) {
      await updateDbStructure(db);
      return true;
    }
    
    // 检查表是否已存在
    const exists = await db.schema.hasTable('book');
    if (!exists) {
      console.log('创建book表...');
      
      // 创建图书表
      await db.schema.createTable('book', function(table) {
        table.increments('id').primary();
        table.string('title').notNullable();
        table.string('video_path').nullable();
        table.string('subtitle_path').nullable();
        table.string('style').nullable();
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('updated_at').defaultTo(db.fn.now());
      });
      
      console.log('创建book_info表...');
      
      // 创建图书信息表
      await db.schema.createTable('book_info', function(table) {
        table.increments('id').primary();
        table.integer('book_id').unsigned().references('id').inTable('book').onDelete('CASCADE');
        table.integer('index').notNullable();
        table.text('text').nullable();
        table.string('start_time').nullable();
        table.string('end_time').nullable();
        table.string('audio_path').nullable();
        table.string('image_path').nullable();
        table.string('video_path').nullable();
        table.text('description').nullable();
        table.integer('draw_status').defaultTo(2); // 添加绘图状态字段，默认为已完成
        table.boolean('is_merged').defaultTo(false);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('updated_at').defaultTo(db.fn.now());
      });
    } else {
      // 如果表已存在，检查是否需要更新结构
      await updateDbStructure(db);
    }
    
    console.log('数据库初始化完成');
    return true;
  } catch (error) {
    console.error('初始化数据库失败:', error);
    return false;
  }
};

// 处理Book相关操作
const handleBookOperations = {
  // 创建新项目
  async createBook(bookData) {
    try {
      const now = new Date().toISOString();
      const book = {
        title: bookData.title,
        video_path: bookData.video_path || null,
        subtitle_path: bookData.subtitle_path || null,
        created_at: now,
        updated_at: now
      };
      
      // 插入数据并返回ID
      const [id] = await db('book').insert(book);
      return { success: true, id };
    } catch (error) {
      console.error('创建项目失败:', error);
      return { success: false, error: error.message };
    }
  },

  // 获取所有项目
  async getAllBooks() {
    try {
      // 按创建时间降序排列
      const books = await db('book').orderBy('created_at', 'desc');
      return { success: true, books };
    } catch (error) {
      console.error('获取项目列表失败:', error);
      return { success: false, error: error.message };
    }
  },

  // 根据ID获取项目
  async getBookById(id) {
    try {
      const book = await db('book').where({ id }).first();
      return { success: true, book };
    } catch (error) {
      console.error(`获取项目(ID: ${id})失败:`, error);
      return { success: false, error: error.message };
    }
  },

  // 更新项目信息
  async updateBook(id, bookData) {
    try {
      const book = await db('book').where({ id }).first();
      if (!book) {
        return { success: false, error: `项目(ID: ${id})不存在` };
      }
      
      const updatedBook = {
        ...bookData,
        updated_at: new Date().toISOString()
      };
      
      await db('book').where({ id }).update(updatedBook);
      return { success: true };
    } catch (error) {
      console.error(`更新项目(ID: ${id})失败:`, error);
      return { success: false, error: error.message };
    }
  },

  // 删除项目
  async deleteBook(id) {
    try {
      // 由于外键约束，删除book会自动删除关联的book_info
      await db('book').where({ id }).delete();
      return { success: true };
    } catch (error) {
      console.error(`删除项目(ID: ${id})失败:`, error);
      return { success: false, error: error.message };
    }
  }
};

// 处理BookInfo相关操作
const handleBookInfoOperations = {
  // 创建项目详细信息
  async createBookInfo(bookInfoData) {
    try {
      const now = new Date().toISOString();
      
      // 处理merged_from字段，如果是数组则转换为JSON字符串
      let mergedFrom = bookInfoData.merged_from;
      if (mergedFrom && Array.isArray(mergedFrom)) {
        mergedFrom = JSON.stringify(mergedFrom);
      }
      
      const bookInfo = {
        book_id: bookInfoData.book_id,
        segment_id: bookInfoData.segment_id || null,
        start_time: bookInfoData.start_time || null,
        end_time: bookInfoData.end_time || null,
        duration: bookInfoData.duration || null,
        text: bookInfoData.text || null,
        audio_path: bookInfoData.audio_path || null,
        image_path: bookInfoData.image_path || null,
        description: bookInfoData.description || null,
        video_path: bookInfoData.video_path || null,
        is_merged: bookInfoData.is_merged || false,
        merged_from: mergedFrom || null,
        created_at: now,
        updated_at: now
      };
      
      // 插入数据并返回ID
      const [id] = await db('book_info').insert(bookInfo);
      return { success: true, id };
    } catch (error) {
      console.error('创建项目详细信息失败:', error);
      return { success: false, error: error.message };
    }
  },

  // 根据项目ID获取详细信息
  async getBookInfoByBookId(bookId) {
    try {
      // 获取该项目的所有字幕段落
      const segments = await db('book_info')
        .where({ book_id: bookId })
        .orderBy('segment_id', 'asc');
      
      return { success: true, bookInfo: segments };
    } catch (error) {
      console.error(`获取项目详细信息(BookID: ${bookId})失败:`, error);
      return { success: false, error: error.message };
    }
  },

  // 更新项目详细信息
  async updateBookInfo(bookId, bookInfoData) {
    try {
      // 检查是否存在对应的book_info记录
      // 当传入的bookId是分镜ID时，直接使用id字段查询
      let exists;
      if (bookInfoData.id) {
        exists = await db('book_info').where({ id: bookInfoData.id }).first();
      } else {
        // 兼容旧代码，当传入的bookId是项目ID时，使用book_id查询
        exists = await db('book_info').where({ book_id: bookId }).first();
      }
      
      if (!exists) {
        return { success: false, error: `项目详细信息不存在，bookId: ${bookId}, id: ${bookInfoData.id || '未指定'}` };
      }
      
      // 处理merged_from字段，如果是数组则转换为JSON字符串
      let updateData = { ...bookInfoData };
      if (updateData.merged_from && Array.isArray(updateData.merged_from)) {
        updateData.merged_from = JSON.stringify(updateData.merged_from);
      }
      
      // 移除id字段，避免尝试更新主键
      if (updateData.id) {
        const { id, ...dataToUpdate } = updateData;
        updateData = dataToUpdate;
      }
      
      updateData.updated_at = new Date().toISOString();
      
      // 使用正确的ID进行更新
      if (bookInfoData.id) {
        // 如果有指定id，则使用id更新特定分镜
        await db('book_info').where({ id: bookInfoData.id }).update(updateData);
      } else {
        // 兼容旧代码，使用book_id更新所有与该项目相关的分镜
        await db('book_info').where({ book_id: bookId }).update(updateData);
      }
      return { success: true };
    } catch (error) {
      console.error(`更新项目详细信息失败:`, error);
      return { success: false, error: error.message };
    }
  },

  // 删除项目详细信息
  async deleteBookInfo(bookId) {
    try {
      // 检查输入参数是否为项目ID还是分镜ID
      const bookRecord = await db('book').where({ id: bookId }).first();
      
      if (bookRecord) {
        // 如果是项目ID，删除项目下所有分镜
        await db('book_info').where({ book_id: bookId }).delete();
      } else {
        // 如果是分镜ID，只删除指定分镜
        await db('book_info').where({ id: bookId }).delete();
      }
      
      return { success: true };
    } catch (error) {
      console.error(`删除项目详细信息失败:`, error);
      return { success: false, error: error.message };
    }
  }
};

module.exports = {
  getDbPath,
  initDatabase,
  handleBookOperations,
  handleBookInfoOperations
}; 