import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);

// src/index/sqlite.ts
import Database from "better-sqlite3";
var MycoIndex = class {
  db;
  constructor(dbPath) {
    this.db = new Database(dbPath);
    this.db.pragma("journal_mode = WAL");
    this.db.pragma("foreign_keys = ON");
    this.init();
  }
  init() {
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS notes (
        path TEXT PRIMARY KEY,
        type TEXT NOT NULL,
        id TEXT NOT NULL,
        title TEXT NOT NULL DEFAULT '',
        content TEXT NOT NULL DEFAULT '',
        frontmatter TEXT NOT NULL DEFAULT '{}',
        created TEXT NOT NULL,
        updated_at TEXT NOT NULL DEFAULT (datetime('now'))
      );

      CREATE INDEX IF NOT EXISTS idx_notes_type ON notes(type);
      CREATE INDEX IF NOT EXISTS idx_notes_id ON notes(id);
      CREATE INDEX IF NOT EXISTS idx_notes_created ON notes(created);
      CREATE INDEX IF NOT EXISTS idx_notes_updated_at ON notes(updated_at);
    `);
  }
  getPragma(name) {
    return this.db.pragma(`${name}`, { simple: true });
  }
  getDb() {
    return this.db;
  }
  upsertNote(note) {
    const stmt = this.db.prepare(`
      INSERT INTO notes (path, type, id, title, content, frontmatter, created, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
      ON CONFLICT(path) DO UPDATE SET
        type = excluded.type,
        id = excluded.id,
        title = excluded.title,
        content = excluded.content,
        frontmatter = excluded.frontmatter,
        created = excluded.created,
        updated_at = datetime('now')
    `);
    stmt.run(
      note.path,
      note.type,
      note.id,
      note.title,
      note.content,
      JSON.stringify(note.frontmatter),
      note.created
    );
  }
  getNoteByPath(notePath) {
    const row = this.db.prepare("SELECT * FROM notes WHERE path = ?").get(notePath);
    if (!row) return null;
    return { ...row, frontmatter: JSON.parse(row.frontmatter) };
  }
  deleteNote(notePath) {
    this.db.prepare("DELETE FROM notes WHERE path = ?").run(notePath);
  }
  query(options) {
    const conditions = [];
    const params = [];
    if (options.type) {
      conditions.push("type = ?");
      params.push(options.type);
    }
    if (options.id) {
      conditions.push("id = ?");
      params.push(options.id);
    }
    if (options.since) {
      conditions.push("created >= ?");
      params.push(options.since);
    }
    if (options.updatedSince) {
      conditions.push("updated_at >= datetime(?)");
      params.push(options.updatedSince);
    }
    if (options.frontmatter) {
      for (const [key, value] of Object.entries(options.frontmatter)) {
        conditions.push(`json_extract(frontmatter, '$.' || ?) = ?`);
        params.push(key, value);
      }
    }
    const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
    const limitClause = options.limit ? "LIMIT ?" : "";
    if (options.limit) params.push(options.limit);
    const sql = `SELECT * FROM notes ${where} ORDER BY created DESC ${limitClause}`;
    const rows = this.db.prepare(sql).all(...params);
    return rows.map((row) => ({ ...row, frontmatter: JSON.parse(row.frontmatter) }));
  }
  queryByIds(ids) {
    if (ids.length === 0) return [];
    const placeholders = ids.map(() => "?").join(",");
    const sql = `SELECT * FROM notes WHERE id IN (${placeholders})`;
    const rows = this.db.prepare(sql).all(...ids);
    return rows.map((row) => ({ ...row, frontmatter: JSON.parse(row.frontmatter) }));
  }
  /** Count notes by type using SQL aggregation (much faster than materializing all rows). */
  countByType() {
    const rows = this.db.prepare("SELECT type, COUNT(*) as count FROM notes GROUP BY type").all();
    const result = {};
    for (const row of rows) result[row.type] = row.count;
    return result;
  }
  /** Count spores grouped by observation_type. */
  sporeCountsByObservationType() {
    const rows = this.db.prepare(
      "SELECT json_extract(frontmatter, '$.observation_type') as obs_type, COUNT(*) as count FROM notes WHERE type = 'spore' GROUP BY obs_type"
    ).all();
    const result = {};
    for (const row of rows) result[row.obs_type ?? "unknown"] = row.count;
    return result;
  }
  close() {
    this.db.close();
  }
};

export {
  MycoIndex
};
//# sourceMappingURL=chunk-TWSTAVLO.js.map