import { loadConfig, type MyOMemoryConfig } from "./config.ts";
import { resolveProjectScope, resolveCwdScope, PERSONAL_SCOPE, type Scope } from "./scope.ts";
import { db } from "./store/db.ts";
import { syncScope, upsertFromFile } from "./store/sync.ts";
import { refreshGraphQuiet } from "./store/graph.ts";
import { scopeHasFiles } from "./store/migrate.ts";
import {
  writeMemoryFile,
  readMemoryFile,
  ulid,
  msToRfc3339,
  type Frontmatter,
} from "./store/markdown.ts";
import { buildContextBlock, type ContextBlock } from "./retrieve/inject.ts";
import { recordInjectionAttempt } from "./store/injection.ts";
import { workingStateBlock } from "./working-state.ts";
import { scanKeywords } from "./capture/keywords.ts";
import {
  TURN_ECHO_WINDOW_MS,
  formatHandoffBlock,
  formatCaptureDropBlock,
  freshCaptures,
  type CaptureRecord,
  type CaptureDropRecord,
} from "./capture/handoff.ts";
import { findDuplicates } from "./store/lifecycle.ts";
import { redact } from "./redact.ts";
import { looksLikeEdgeVerdict } from "./graph/admissibility.ts";

/**
 * Host-agnostic plugin core (D60). Both opencode host generations adapt to
 * this module: the v1 plugin (src/index.ts `server`) and the v2 plugin
 * (src/opencode-v2.ts `setup`). Host-specific glue — tool registration and
 * hook shapes — stays in the adapters; everything memory-shaped lives here.
 */
export const PLUGIN_ID = "open-memex";

export interface PluginState {
  cfg: MyOMemoryConfig;
  scope: Scope;
  /** Sessions that already received the one-time context injection. */
  injectedSessions: Set<string>;
  /**
   * D98 (issue #92): consecutive failed injection attempts per session.
   * The once-guard used to be consumed by the attempt itself — a single
   * transient failure on the first turn lost the block for the whole
   * session. The session is marked only on a successful push now, and a
   * failure retries on the next model call, up to this many attempts;
   * after that the session gives up (and the failure stays visible in the
   * persistent injection record, so it is diagnosable instead of silent).
   */
  injectionFailures: Map<string, number>;
  /** Sessions that already received the D89 working-state surfacing. */
  workingStateSessions: Set<string>;
  /** D98: same retry discipline as `injectionFailures`, for the note. */
  workingStateFailures: Map<string, number>;
  /**
   * D73: what the keyword hook stored this session, so the agent can be told
   * before it re-saves the same statement. In memory only, like
   * `injectedSessions` — never persisted, pruned by the turn window.
   */
  captures: Map<string, CaptureRecord[]>;
  /**
   * D94: over-cap keyword drops this session (too-long only). The capture
   * proceeds with no agent in the loop, so without this the agent never
   * learns the sentence was dropped - it surfaces once via the hand-off
   * note. In memory only, same discipline as `captures`.
   */
  drops: Map<string, CaptureDropRecord[]>;
}

/**
 * Resolve the project scope for a host working directory and bring the
 * index up to date. Never throws: a broken store must not keep the host
 * from starting — failures land in the host's log instead.
 */
export function bootstrapPlugin(root: string): PluginState {
  const cfg = loadConfig();
  const scope = resolveProjectScope(root);
  try {
    db();
    syncScope(scope.key);
    syncScope(PERSONAL_SCOPE.key);
    if (cfg.logLevel === "debug") {
      console.log(`[open-memex] loaded. scope=${scope.key}`);
    }
    // If a git remote was added *after* memories were first captured, the
    // scope key changes (cwd-hash -> origin-hash). Detect the legacy dir on
    // disk and tell the user how to migrate. We do NOT auto-migrate: two
    // different repos at the same cwd would collide.
    const cwdScope = resolveCwdScope(root);
    if (cwdScope.key !== scope.key && scopeHasFiles(cwdScope.key)) {
      console.warn(
        `[open-memex] found memories under legacy scope key "${cwdScope.key}". ` +
          `Current project scope is "${scope.key}". ` +
          `To move them: npm run cli -- migrate --from ${cwdScope.key} --to ${scope.key}`,
      );
    }
  } catch (err) {
    console.error("[open-memex] init failed:", err);
  }
  return { cfg, scope, injectedSessions: new Set<string>(), injectionFailures: new Map<string, number>(), workingStateSessions: new Set<string>(), workingStateFailures: new Map<string, number>(), captures: new Map(), drops: new Map() };
}

/**
 * Keyword capture (§ capture): scan one user message for "remember …"
 * triggers and save each hit. Shared by the v1 `chat.message` hook and
 * the v2 session `prompt` hook — both hand us the message text and the
 * session id. The session id is what makes the D73 hand-off possible: without
 * it the agent never learns the sentence is already stored.
 */
export function captureFromText(
  text: string,
  state: PluginState,
  sessionID?: string,
): void {
  const { cfg, scope } = state;
  if (!cfg.keywordCaptureEnabled || !text) return;
  // D94: scanKeywords over detectKeywords - the dropped matches come back
  // too. Over-cap (too-long) drops are recorded against the session so the
  // D73 hand-off note can surface them; too-short stays debug-log-only.
  const scan = scanKeywords(text, cfg);
  const hits = scan.hits;
  for (const d of scan.dropped) {
    if (d.reason !== "too-long") continue;
    recordCaptureDrop(state, sessionID, { content: d.content, at: Date.now() });
  }
  for (const h of hits) {
    const { content, hadSecret, matchedPattern } = redact(h.content, cfg.redactPatterns);
    // Secrets are masked (first 4 chars kept) and the capture proceeds;
    // skip only when nothing usable remains.
    if (content.length === 0) continue;
    // D97: an edge verdict is not a memory — same refusal as memory_add.
    // A verdict-shaped body pasted by the user must not slip in through
    // keyword capture; verdicts enter only through `graph verdict`.
    // Ordering note: like memory_add, this runs on the redacted body —
    // redaction must preserve JSON structure (it masks secret values
    // only).
    if (looksLikeEdgeVerdict(content)) {
      if (cfg.logLevel === "debug") {
        console.log("[open-memex] keyword capture skipped an edge verdict (use `graph verdict`)");
      }
      continue;
    }
    if (hadSecret && cfg.logLevel === "debug") {
      console.log(`[open-memex] keyword capture masked secret (${matchedPattern})`);
    }
    // Personal patterns ("remember for me" / "记住（个人）") force the personal scope.
    const target = h.personal ? PERSONAL_SCOPE : scope;
    // Dedup (§3.4): skip exact duplicates captured before.
    if (findDuplicates(target.key, content).exact) continue;
    const now = Date.now();
    const rfc = msToRfc3339(now);
    const fm: Frontmatter = {
      id: ulid(),
      schema_version: 2,
      scope_key: target.key,
      scope: target.kind === "project" ? "project" : "personal",
      visibility: target.kind === "project" ? "internal" : "private",
      project_name: target.projectName,
      type: "fact",
      role: "knowledge",
      importance: "normal",
      status: "active",
      tags: ["keyword"],
      source: "keyword",
      created_at: rfc,
      updated_at: rfc,
      supersedes: null,
      superseded_by: null,
      review_state: "draft",
      proposed_by: null,
      approved_by: null,
      derived_from: null,
      review_note: null,
      review_history: [],
    };
    try {
      const { filePath } = writeMemoryFile(fm, content);
      const mf = readMemoryFile(filePath);
      if (mf) upsertFromFile(mf);
      // D91 ingest: keyword capture is a normal write path too — the graph
      // must not go stale until the next ops/CLI write. Personal no-ops.
      refreshGraphQuiet(target.key, cfg);
      // Capture feedback: always visible (not debug-only) — the user said
      // "记住…", they should see that it landed. The opencode plugin API
      // offers no toast channel, so the plugin log is the feedback surface.
      const preview = content.length > 60 ? content.slice(0, 60) + "…" : content;
      console.log(`[open-memex] remembered → ${target.kind} scope: "${preview}"`);
      // D73 hand-off: the agent gets told about this capture in the turn's
      // system context, so it does not save the same statement again.
      recordCapture(state, sessionID, { id: fm.id, scopeKey: target.key, content, at: now });
    } catch (err) {
      console.error("[open-memex] keyword capture failed:", err);
    }
  }
}

/** Note one hook capture against its session (D73). No-op without a session. */
function recordCapture(
  state: PluginState,
  sessionID: string | undefined,
  record: CaptureRecord,
): void {
  if (!sessionID) return;
  const list = state.captures.get(sessionID) ?? [];
  list.push(record);
  state.captures.set(sessionID, list);
}

/** Note one over-cap drop against its session (D94). No-op without a session. */
function recordCaptureDrop(
  state: PluginState,
  sessionID: string | undefined,
  record: CaptureDropRecord,
): void {
  if (!sessionID) return;
  const list = state.drops.get(sessionID) ?? [];
  list.push(record);
  state.drops.set(sessionID, list);
}

/**
 * D73 hand-off note (a): what the keyword hook already stored for this
 * session, delivered once per capture into the turn's system context. The
 * agent cannot avoid re-saving a statement it cannot see is stored, so the
 * store tells it. D94: over-cap keyword drops ride the same note, so the
 * agent learns a long match was dropped and can re-save a shorter version.
 * Returns "" when there is nothing new to hand off; stale records are
 * pruned (in-memory only, like `injectedSessions`).
 *
 * Both host adapters push this from their system/context hook — the one that
 * runs before the model request, i.e. after `chat.message` / `prompt`.
 */
export function captureHandoff(sessionID: string, state: PluginState): string {
  if (!sessionID) return "";
  const now = Date.now();
  const list = state.captures.get(sessionID);
  let capturesBlock = "";
  if (list && list.length > 0) {
    const fresh = freshCaptures(list, now);
    if (fresh.length !== list.length) {
      if (fresh.length === 0) state.captures.delete(sessionID);
      else state.captures.set(sessionID, fresh);
    }
    const pending = fresh.filter((r) => !r.delivered);
    if (pending.length > 0) {
      for (const r of pending) r.delivered = true;
      capturesBlock = formatHandoffBlock(pending);
    }
  }
  const dropList = state.drops.get(sessionID);
  let dropsBlock = "";
  if (dropList && dropList.length > 0) {
    const fresh = dropList.filter((d) => now - d.at <= TURN_ECHO_WINDOW_MS);
    if (fresh.length !== dropList.length) {
      if (fresh.length === 0) state.drops.delete(sessionID);
      else state.drops.set(sessionID, fresh);
    }
    const pending = fresh.filter((d) => !d.delivered);
    if (pending.length > 0) {
      for (const d of pending) d.delivered = true;
      dropsBlock = formatCaptureDropBlock(pending);
    }
  }
  if (capturesBlock && dropsBlock) return `${capturesBlock}\n\n${dropsBlock}`;
  return capturesBlock || dropsBlock;
}

/**
 * First-turn context injection: exactly once per session. The host adapter
 * supplies `push` (v1: output.system.push; v2: the session context hook's
 * system array). Returns true when a block was pushed.
 */
/**
 * D98: how many failed injection attempts a session tolerates before the
 * once-guard gives up on it. A failure is retried on the next model call
 * (the v2 `context` hook fires before every model call, so the retry lands
 * on the very next turn); a deterministic failure must not pay for a
 * rebuild + a stderr line on every turn forever, so the cap stops the
 * retries — and the persistent injection record keeps the failure visible.
 */
export const MAX_INJECTION_ATTEMPTS = 3;

function noteFailure(failures: Map<string, number>, sessionID: string): void {
  failures.set(sessionID, (failures.get(sessionID) ?? 0) + 1);
}

function recordAttempt(
  sessionID: string,
  ok: boolean,
  profileCount: number,
  projectCount: number,
  error: unknown,
): void {
  recordInjectionAttempt({
    sessionId: sessionID,
    atMs: Date.now(),
    ok,
    profileCount,
    projectCount,
    error: ok ? null : error instanceof Error ? error.message : String(error),
  });
}

export function injectOnce(
  sessionID: string,
  state: PluginState,
  push: (block: string) => void,
): boolean {
  const { cfg, scope } = state;
  if (!cfg.injectOnFirstTurn) return false;
  if (state.injectedSessions.has(sessionID)) return false;
  if ((state.injectionFailures.get(sessionID) ?? 0) >= MAX_INJECTION_ATTEMPTS) {
    // Gave up on this session: move it to the done set and drop the
    // failure count, so the maps stay bounded. Deleting the count alone
    // would reset the cap and retry the session forever — the entry IS
    // the cap state. The persistent record keeps the failure visible.
    state.injectedSessions.add(sessionID);
    state.injectionFailures.delete(sessionID);
    return false;
  }
  // D98 (issue #92 part 1): the session used to be marked injected BEFORE
  // the block was built, so one transient failure on the first turn — a
  // throwing graph first-build, a counter write, the host's system push —
  // lost the block for the whole session with no retry. The mark now
  // happens only after a successful push; a failure retries next turn.
  let built: ContextBlock | null;
  try {
    built = buildContextBlock(scope, cfg);
  } catch (err) {
    noteFailure(state.injectionFailures, sessionID);
    recordAttempt(sessionID, false, 0, 0, err);
    console.error("[open-memex] context injection failed:", err);
    return false;
  }
  if (!built) {
    // Empty store: nothing a retry could add, so this counts as done —
    // later turns must not pay for a rebuild on every model call.
    state.injectedSessions.add(sessionID);
    recordAttempt(sessionID, true, 0, 0, null);
    return false;
  }
  try {
    push(built.block);
  } catch (err) {
    noteFailure(state.injectionFailures, sessionID);
    recordAttempt(sessionID, false, built.profileCount, built.projectCount, err);
    console.error("[open-memex] context injection failed:", err);
    return false;
  }
  state.injectedSessions.add(sessionID);
  state.injectionFailures.delete(sessionID);
  recordAttempt(sessionID, true, built.profileCount, built.projectCount, null);
  return true;
}

/**
 * §3.6 (D89): surface the working-state note once per session, alongside
 * the context injection. Scratch state, not knowledge — the block itself
 * says what it is. Exactly-once uses the same in-memory Set discipline as
 * `injectOnce` (not persisted; restarting the host re-surfaces). Expired
 * or missing notes surface nothing.
 */
export function surfaceWorkingStateOnce(
  sessionID: string,
  state: PluginState,
  push: (block: string) => void,
): boolean {
  const { cfg, scope } = state;
  if (!cfg.workingStateEnabled) return false;
  if (state.workingStateSessions.has(sessionID)) return false;
  if ((state.workingStateFailures.get(sessionID) ?? 0) >= MAX_INJECTION_ATTEMPTS) {
    // Same as injectOnce above: cap exhaustion moves the session to the
    // done set so the failure count can be dropped without resetting
    // the cap.
    state.workingStateSessions.add(sessionID);
    state.workingStateFailures.delete(sessionID);
    return false;
  }
  // D98: same mark-on-success discipline as `injectOnce` — the note used
  // to be marked surfaced before it was built, so one transient failure
  // lost it for the session. (No persistent record: the injection table
  // is about the [OPEN-MEMEX] block; a failed note still logs here.)
  let block: string | null;
  try {
    block = workingStateBlock(scope.key, scope.projectName, cfg);
  } catch (err) {
    noteFailure(state.workingStateFailures, sessionID);
    console.error("[open-memex] working-state surfacing failed:", err);
    return false;
  }
  if (!block) {
    state.workingStateSessions.add(sessionID);
    return false;
  }
  try {
    push(block);
  } catch (err) {
    noteFailure(state.workingStateFailures, sessionID);
    console.error("[open-memex] working-state surfacing failed:", err);
    return false;
  }
  state.workingStateSessions.add(sessionID);
  state.workingStateFailures.delete(sessionID);
  return true;
}
