import * as crypto from "node:crypto";
import type { Kysely } from "kysely";
import { logInfo } from "@/lib/logger";
import { elevenLabsRequest } from "@/lib/elevenlabs/client";
import { env } from "@/lib/env";
import { ConsoleSettingsRepository } from "@/internal/repository/admin_console/console_settings";
import { KevoRepositoryFromDb } from "./kevo.repository";
import type { KevoKnowledgeEntry } from "@/internal/datastore/kevo.types";

/**
 * Publishing approved knowledge into ONE managed ElevenLabs KB document
 * (PLAN.md part 5). The document id lives in console_settings under
 * SETTINGS_KEY — created on first publish, content-updated afterwards
 * (PATCH re-chunks and re-embeds automatically, per API_NOTES.md §2).
 */

export const KB_DOCUMENT_NAME = "Kevo – Verified Corrections & Amenity Map";
const SETTINGS_KEY = "kevo.kb_document";

export const renderKnowledgeMarkdown = (
  entries: KevoKnowledgeEntry[],
  now = new Date(),
): string => {
  const byProperty = new Map<string, KevoKnowledgeEntry[]>();
  for (const e of entries) {
    const key = e.property?.trim() || "General";
    byProperty.set(key, [...(byProperty.get(key) ?? []), e]);
  }
  const sections = [...byProperty.entries()]
    .sort(([a], [b]) => (a === "General" ? 1 : b === "General" ? -1 : a.localeCompare(b)))
    .map(([property, items]) => {
      const lines = items.map((e) => {
        const aliases = e.aliases?.length
          ? ` Also known as: ${e.aliases.map((a) => `"${a}"`).join(", ")}.`
          : "";
        return `- **${e.entity}**: ${e.verified_text.trim()}${aliases}`;
      });
      return `## ${property}\n\n${lines.join("\n")}`;
    });

  const date = now.toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
  return [
    `# ${KB_DOCUMENT_NAME}`,
    "",
    `Verified facts approved by the Karma team. Treat these as authoritative — they override conflicting information in other documents. Last updated ${date}.`,
    "",
    ...sections,
    "",
  ].join("\n");
};

export const contentHash = (content: string): string =>
  crypto.createHash("sha256").update(content).digest("hex");

export const KevoPublishServices = (pool: Kysely<unknown>) => {
  const repo = KevoRepositoryFromDb(pool);
  const settings = new ConsoleSettingsRepository(pool);

  const getDocumentId = async (): Promise<string | null> => {
    const row = await settings.get(SETTINGS_KEY);
    const value = row?.value as { document_id?: string } | null;
    return value?.document_id ?? null;
  };

  return {
    /** Diff preview for the console: content, hash, and change status. */
    async preview() {
      const entries = await repo.publishableEntries();
      const content = renderKnowledgeMarkdown(entries);
      const hash = contentHash(content);
      const last = await repo.lastSuccessfulPublish();
      return {
        content,
        hash,
        entries_count: entries.length,
        document_id: await getDocumentId(),
        last_published_hash: last?.content_hash ?? null,
        last_published_at: last?.published_at ?? null,
        unchanged: last?.content_hash === hash,
      };
    },

    async publish(publishedBy: string) {
      const entries = await repo.publishableEntries();
      if (entries.length === 0) {
        throw new Error("Nothing to publish: no approved knowledge entries.");
      }
      const content = renderKnowledgeMarkdown(entries);
      const hash = contentHash(content);

      const last = await repo.lastSuccessfulPublish();
      if (last?.content_hash === hash) {
        return { skipped: true as const, hash, entries_count: entries.length };
      }

      let documentId = await getDocumentId();
      try {
        if (!documentId) {
          // First publish: create the document, remember it, attach to agent.
          const created = await elevenLabsRequest<{ id: string }>(
            "/v1/convai/knowledge-base/text",
            { method: "POST", body: { name: KB_DOCUMENT_NAME, text: content } },
          );
          documentId = created.id;
          await settings.put(
            SETTINGS_KEY,
            { document_id: documentId, name: KB_DOCUMENT_NAME },
            publishedBy,
          );
          await this.attachToAgent(documentId);
        } else {
          // Content update re-indexes automatically (API_NOTES.md §2).
          await elevenLabsRequest(
            `/v1/convai/knowledge-base/${documentId}`,
            { method: "PATCH", body: { content } },
          );
        }
      } catch (err) {
        await repo.insertPublishLog({
          kb_document_id: documentId,
          entries_count: entries.length,
          content_hash: hash,
          published_by: publishedBy,
          result: `failed: ${err instanceof Error ? err.message.slice(0, 500) : err}`,
        });
        throw err;
      }

      await repo.markEntriesPublished(entries.map((e) => e.id));
      await repo.insertPublishLog({
        kb_document_id: documentId,
        entries_count: entries.length,
        content_hash: hash,
        published_by: publishedBy,
        result: "succeeded",
      });
      await repo.insertAudit({
        action: "publish.succeeded",
        actor_email: publishedBy,
        metadata: { document_id: documentId, entries: entries.length, hash },
      });
      logInfo(`[Kevo] published ${entries.length} entries to ${documentId}`);
      return { skipped: false as const, hash, entries_count: entries.length };
    },

    /**
     * Merge-safe attach: read the agent's knowledge_base list, append our
     * locator if absent, write the list back. Never drops other documents.
     */
    async attachToAgent(documentId: string) {
      const agentId = env.GetString("ELEVENLABS_AGENT_ID");
      const agent = await elevenLabsRequest<{
        conversation_config: {
          agent: {
            prompt: {
              knowledge_base?: Array<{
                type: string;
                id: string;
                name: string;
                usage_mode?: string;
              }>;
            };
          };
        };
      }>(`/v1/convai/agents/${agentId}`);

      const kb = agent.conversation_config.agent.prompt.knowledge_base ?? [];
      if (kb.some((d) => d.id === documentId)) return;
      await elevenLabsRequest(`/v1/convai/agents/${agentId}`, {
        method: "PATCH",
        body: {
          conversation_config: {
            agent: {
              prompt: {
                knowledge_base: [
                  ...kb,
                  {
                    type: "text",
                    id: documentId,
                    name: KB_DOCUMENT_NAME,
                    usage_mode: "auto",
                  },
                ],
              },
            },
          },
        },
      });
    },
  };
};
