import * as fs from 'node:fs';
import * as path from 'node:path';
import { decryptDatabase } from './wcdb_codec.js';

export interface DecryptOptions {
  srcDb: string;
  rawKey: Buffer;
  workDir: string;
}

/**
 * 把加密 DB 原地 copy 到 workDir/src/ 再解密到 workDir/decrypted/ 下,返回明文 DB 路径。
 * 微信持有独占锁,必须先 copy 副本; -wal / -shm 如存在也尝试 copy(锁文件 copy 失败可忽略)。
 * 解密目标 DB 自带完整数据,删掉残留 -wal / -shm,避免 better-sqlite3 误读。
 */
export function decryptDbToWorkDir(opts: DecryptOptions): string {
  const { srcDb, rawKey, workDir } = opts;
  const srcDir = path.join(workDir, 'src');
  const outDir = path.join(workDir, 'decrypted');
  fs.mkdirSync(srcDir, { recursive: true });
  fs.mkdirSync(outDir, { recursive: true });

  const name = path.basename(srcDb);
  const srcCopy = path.join(srcDir, name);
  fs.copyFileSync(srcDb, srcCopy);
  for (const suffix of ['-wal', '-shm']) {
    const s = srcDb + suffix;
    if (fs.existsSync(s)) {
      try { fs.copyFileSync(s, srcCopy + suffix); } catch { /* 锁文件 copy 失败可忽略 */ }
    }
  }

  const encrypted = fs.readFileSync(srcCopy);
  const decrypted = decryptDatabase(encrypted, rawKey);
  const outPath = path.join(outDir, name);
  fs.writeFileSync(outPath, decrypted);
  for (const suffix of ['-wal', '-shm']) {
    const p = outPath + suffix;
    if (fs.existsSync(p)) {
      try { fs.unlinkSync(p); } catch { /* ignore */ }
    }
  }
  return outPath;
}
