const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

console.log('=== 清理锁文件脚本 ===')

// 获取用户数据路径
function getUserDataPath() {
  const platform = process.platform
  const home = process.env.HOME || process.env.USERPROFILE
  
  if (platform === 'win32') {
    return path.join(process.env.APPDATA, 'dify-market-manager-gui')
  } else if (platform === 'darwin') {
    return path.join(home, 'Library', 'Application Support', 'dify-market-manager-gui')
  } else {
    return path.join(home, '.config', 'dify-market-manager-gui')
  }
}

// 可能的锁文件位置
const possibleLockFiles = [
  // 新的应用名称
  path.join(getUserDataPath(), 'single-instance-lock'),
  path.join(getUserDataPath(), 'lockfile'),
  path.join(getUserDataPath(), '.lock'),
  
  // 旧的应用名称
  path.join(process.env.APPDATA || '', 'market-manager-gui', 'single-instance-lock'),
  path.join(process.env.APPDATA || '', 'market-manager-gui', 'lockfile'),
  path.join(process.env.APPDATA || '', 'market-manager-gui', '.lock'),
  
  // 当前目录
  path.join(process.cwd(), 'single-instance-lock'),
  path.join(process.cwd(), 'lockfile'),
  path.join(process.cwd(), '.lock'),
  
  // 临时目录
  path.join(process.env.TEMP || '', 'single-instance-lock'),
  path.join(process.env.TEMP || '', 'lockfile'),
  path.join(process.env.TEMP || '', '.lock'),
]

console.log('用户数据路径:', getUserDataPath())
console.log('当前目录:', process.cwd())

let cleanedCount = 0

// 清理锁文件
for (const lockFile of possibleLockFiles) {
  if (fs.existsSync(lockFile)) {
    try {
      console.log(`发现锁文件: ${lockFile}`)
      
      // 读取锁文件内容
      const content = fs.readFileSync(lockFile, 'utf8')
      console.log(`锁文件内容: ${content}`)
      
      // 尝试删除文件
      fs.unlinkSync(lockFile)
      console.log(`✅ 成功删除: ${lockFile}`)
      cleanedCount++
      
    } catch (error) {
      console.log(`❌ 删除失败: ${lockFile}`, error.message)
      
      // 在 Windows 上尝试使用 del 命令
      if (process.platform === 'win32') {
        try {
          execSync(`del /F /Q "${lockFile}"`, { stdio: 'ignore' })
          console.log(`✅ 使用 del 命令删除: ${lockFile}`)
          cleanedCount++
        } catch (delError) {
          console.log(`❌ del 命令也失败: ${lockFile}`)
        }
      }
    }
  }
}

console.log(`\n清理完成，共删除 ${cleanedCount} 个锁文件`)

// 检查是否有相关进程在运行
if (process.platform === 'win32') {
  try {
    console.log('\n检查相关进程:')
    const result = execSync('tasklist /FI "IMAGENAME eq 龙岗区百千万AI智能体共创平台.exe" /FO CSV /NH', { encoding: 'utf8' })
    console.log(result)
  } catch (error) {
    console.log('没有找到相关进程')
  }
}

console.log('\n清理完成！现在可以重新启动应用了。') 