import * as path from 'node:path';
import * as fs from 'node:fs';

export class DbPaths {
  readonly messageDb: string;
  readonly bizMessageDb: string;
  readonly mediaDb: string;
  readonly messageFtsDb: string;
  readonly messageResourceDb: string;
  readonly contactDb: string;
  readonly contactFtsDb: string;
  readonly sessionDb: string;
  readonly generalDb: string;
  readonly favoriteDb: string;
  readonly favoriteFtsDb: string;
  readonly hardlinkDb: string;
  readonly headImageDb: string;
  readonly emoticonDb: string;
  readonly bizChatDb: string;
  readonly snsDb: string;
  readonly solitaireDb: string;

  constructor(public readonly seedDir: string) {
    const d = (sub: string) => path.join(seedDir, 'db_storage', sub);
    this.messageDb         = d(path.join('message', 'message_0.db'));
    this.bizMessageDb      = d(path.join('message', 'biz_message_0.db'));
    this.mediaDb           = d(path.join('message', 'media_0.db'));
    this.messageFtsDb      = d(path.join('message', 'message_fts.db'));
    this.messageResourceDb = d(path.join('message', 'message_resource.db'));
    this.contactDb         = d(path.join('contact', 'contact.db'));
    this.contactFtsDb      = d(path.join('contact', 'contact_fts.db'));
    this.sessionDb         = d(path.join('session', 'session.db'));
    this.generalDb         = d(path.join('general', 'general.db'));
    this.favoriteDb        = d(path.join('favorite', 'favorite.db'));
    this.favoriteFtsDb     = d(path.join('favorite', 'favorite_fts.db'));
    this.hardlinkDb        = d(path.join('hardlink', 'hardlink.db'));
    this.headImageDb       = d(path.join('head_image', 'head_image.db'));
    this.emoticonDb        = d(path.join('emoticon', 'emoticon.db'));
    this.bizChatDb         = d(path.join('bizchat', 'bizchat.db'));
    this.snsDb             = d(path.join('sns', 'sns.db'));
    this.solitaireDb       = d(path.join('solitaire', 'solitaire.db'));
  }

  allDbs(): string[] {
    return [
      this.messageDb, this.bizMessageDb, this.mediaDb, this.messageFtsDb, this.messageResourceDb,
      this.contactDb, this.contactFtsDb, this.sessionDb, this.generalDb, this.favoriteDb,
      this.favoriteFtsDb, this.hardlinkDb, this.headImageDb, this.emoticonDb, this.bizChatDb,
      this.snsDb, this.solitaireDb,
    ];
  }

  /** 读 DB 文件前 16B 作为 salt。 */
  static readSalt(dbPath: string): Buffer | null {
    if (!fs.existsSync(dbPath)) return null;
    const fd = fs.openSync(dbPath, 'r');
    try {
      const buf = Buffer.alloc(16);
      if (fs.readSync(fd, buf, 0, 16, 0) !== 16) return null;
      return buf;
    } finally {
      fs.closeSync(fd);
    }
  }

  /** 自动找用户 Documents/xwechat_files/ 下最近修改的 seed 目录 (排除 all_users / Backup)。 */
  static autoFindSeedDir(): string | null {
    const home = process.env.USERPROFILE || process.env.HOME || '';
    const root = path.join(home, 'Documents', 'xwechat_files');
    if (!fs.existsSync(root)) return null;
    const entries = fs.readdirSync(root, { withFileTypes: true })
      .filter(d => d.isDirectory())
      .map(d => d.name)
      .filter(n => n !== 'all_users' && n !== 'Backup');
    if (entries.length === 0) return null;
    const withMtime = entries.map(name => {
      const p = path.join(root, name);
      return { name, p, mtime: fs.statSync(p).mtimeMs };
    }).sort((a, b) => b.mtime - a.mtime);
    return withMtime[0].p;
  }
}
