/** LTM episodic memory — conversation summaries (English, LLM-to-LLM) */

import * as Log from "@saeeol/core/util/log"
import * as Embedder from "@/provider/local/embedder"
import type { Memory } from "@/ltm/types"

const log = Log.create({ service: "ltm/memory/episodic" })

/** Create an episodic memory from a conversation exchange */
export async function fromConversation(
  sessionID: string,
  projectID: string | undefined,
  userMsg: string,
  assistantMsg: string,
): Promise<Memory | undefined> {
  if (assistantMsg.length < 50) return undefined

  const summary = summarize(userMsg, assistantMsg)
  if (!summary) return undefined

  try {
    const vector = await Embedder.embedOne(summary)
    return {
      id: `epi:${sessionID}:${Date.now()}`,
      type: "episodic",
      content: assistantMsg.slice(0, 500),
      summary,
      vector,
      metadata: {
        source: `session:${sessionID}`,
        timestamp: Date.now(),
        projectID,
        sessionID,
        tags: extractTags(userMsg + " " + assistantMsg),
      },
    }
  } catch (e) {
    log.error("failed to create episodic memory", { error: e })
    return undefined
  }
}

/** Build a rule-based summary (no LLM call) */
function summarize(user: string, assistant: string): string {
  const userBrief = user.slice(0, 120).replace(/\n/g, " ").trim()
  const assistantBrief = assistant.slice(0, 200).replace(/\n/g, " ").trim()
  return `user asked: ${userBrief}\nassistant did: ${assistantBrief}`
}

/** Extract topic tags from message content */
function extractTags(msg: string): string[] {
  const tags: string[] = []
  const lower = msg.toLowerCase()

  const patterns: Array<{ keyword: string; tag: string }> = [
    { keyword: "bug", tag: "bug" },
    { keyword: "fix", tag: "fix" },
    { keyword: "refactor", tag: "refactor" },
    { keyword: "test", tag: "test" },
    { keyword: "config", tag: "config" },
    { keyword: "api", tag: "api" },
    { keyword: "auth", tag: "auth" },
    { keyword: "deploy", tag: "deploy" },
    { keyword: "error", tag: "error" },
    { keyword: "crash", tag: "crash" },
    { keyword: "performance", tag: "perf" },
    { keyword: "security", tag: "security" },
    { keyword: "database", tag: "database" },
    { keyword: "migration", tag: "migration" },
    { keyword: "feature", tag: "feature" },
  ]

  for (const { keyword, tag } of patterns) {
    if (lower.includes(keyword) && !tags.includes(tag)) tags.push(tag)
  }

  return tags
}

/** Check if summarization should trigger at this turn count */
export function shouldSummarize(turnCount: number, interval: number): boolean {
  return turnCount > 0 && turnCount % interval === 0
}
