/**
 * Session-start injection attempts (D98, issue #92 part 1).
 *
 * The plugin's first-turn injection used to fail silently: the only trace
 * was a `console.error` on the plugin process's stderr, which no OpenCode
 * UI surface shows, and the session was marked injected before the block
 * was even built — so one transient failure lost the block for the whole
 * session with no way to tell afterwards except asking the model.
 *
 * This module records every injection attempt (success or failure) in a
 * small `injection_attempts` table, created `IF NOT EXISTS` beside the D77
 * counters and never dropped by a rebuild (same discipline: accumulated
 * telemetry with no Markdown source to rebuild from). `doctor` and
 * `sync-status` read the latest row, so a failed injection is visible
 * without interrogating the model. The table is capped at the newest 20
 * rows; recording never throws into the injection path (a failure to
 * record is logged and swallowed — the diagnostic must not break the
 * thing it diagnoses). Reading the latest row never throws either — a
 * read failure degrades to "no record" instead of killing the caller
 * (review Minor 1: `sync-status` prints this line after its own work).
 */
import { db } from "./db.ts";

export interface InjectionAttempt {
  sessionId: string;
  atMs: number;
  ok: boolean;
  profileCount: number;
  projectCount: number;
  error: string | null;
}

const MAX_ROWS = 20;
const MAX_ERROR_CHARS = 240;

export function recordInjectionAttempt(a: InjectionAttempt): void {
  try {
    const d = db();
    d.prepare(
      `INSERT INTO injection_attempts
         (session_id, at_ms, ok, profile_count, project_count, error)
       VALUES (?, ?, ?, ?, ?, ?)`,
    ).run(
      a.sessionId,
      a.atMs,
      a.ok ? 1 : 0,
      a.profileCount,
      a.projectCount,
      a.error ? a.error.slice(0, MAX_ERROR_CHARS) : null,
    );
    d.prepare(
      `DELETE FROM injection_attempts WHERE id NOT IN
         (SELECT id FROM injection_attempts ORDER BY at_ms DESC, id DESC LIMIT ?)`,
    ).run(MAX_ROWS);
  } catch (err) {
    console.error("[open-memex] could not record injection attempt:", err);
  }
}

export function lastInjectionAttempt(): InjectionAttempt | null {
  // Minor 1: the read never throws (same discipline as the record path).
  let row: {
    session_id: string;
    at_ms: number;
    ok: number;
    profile_count: number;
    project_count: number;
    error: string | null;
  } | undefined;
  try {
    row = db()
    .prepare(
      `SELECT session_id, at_ms, ok, profile_count, project_count, error
       FROM injection_attempts ORDER BY at_ms DESC, id DESC LIMIT 1`,
    )
    .get() as
    | {
        session_id: string;
        at_ms: number;
        ok: number;
        profile_count: number;
        project_count: number;
        error: string | null;
      }
    | undefined;
  } catch (err) {
    console.error("[open-memex] could not read last injection attempt:", err);
    return null;
  }
  if (!row) return null;
  return {
    sessionId: row.session_id,
    atMs: row.at_ms,
    ok: row.ok === 1,
    profileCount: row.profile_count,
    projectCount: row.project_count,
    error: row.error,
  };
}

/** One line for `doctor` and `sync-status` — same wording in both places. */
export function formatInjectionAttempt(a: InjectionAttempt): string {
  const when = new Date(a.atMs).toISOString();
  const id = a.sessionId.length > 8 ? `${a.sessionId.slice(0, 8)}…` : a.sessionId;
  if (a.ok) {
    return `ok — session ${id}, ${a.profileCount} profile + ${a.projectCount} project items, ${when}`;
  }
  return `FAILED — session ${id}, ${a.error ?? "unknown error"}, ${when} (a new session retries)`;
}
