import { getPocketBase } from '../lib/pocketbase.js';
import type { Chunk, DraftKB, WrittenTopic } from '../types.js';

export async function writeToPocketBase(
  draftKB: DraftKB,
  documentId: string,
  chunkCount: number,
): Promise<WrittenTopic[]> {
  const pb = await getPocketBase();

  await pb.collection('source_documents').update(documentId, {
    status: 'processed',
    chunk_count: chunkCount,
    ingested_at: new Date().toISOString(),
  });

  const writtenTopics: WrittenTopic[] = [];
  // title → PocketBase topic ID (for relationship resolution)
  const topicIdByTitle = new Map<string, string>();

  // Pass 1: create all themes and topics (without relationships)
  for (const theme of draftKB.themes) {
    const themeRecord = await pb.collection('themes').create({
      title: theme.title,
      description: theme.description,
      status: 'draft',
      source_documents: [documentId],
    });

    for (const topic of theme.topics) {
      const topicRecord = await pb.collection('topics').create({
        theme: themeRecord.id,
        title: topic.title,
        body: topic.body,
        difficulty: topic.difficulty,
        complexity_weight: topic.complexityWeight,
        status: 'draft',
        key_terms: topic.keyTerms,
        qdrant_chunk_ids: [],
        related_topics: [],
        prerequisite_topics: [],
        contrast_topics: [],
      });

      topicIdByTitle.set(topic.title.toLowerCase().trim(), topicRecord.id);

      writtenTopics.push({
        id: topicRecord.id,
        title: topic.title,
        themeId: themeRecord.id,
        body: topic.body,
        sourceChunkIds: topic.sourceChunkIds,
      });
    }
  }

  // Pass 2: resolve relationships (title → ID lookup)
  for (const theme of draftKB.themes) {
    for (const topic of theme.topics) {
      const topicId = topicIdByTitle.get(topic.title.toLowerCase().trim());
      if (!topicId) continue;

      const resolve = (titles: string[]): string[] =>
        titles
          .map(t => topicIdByTitle.get(t.toLowerCase().trim()))
          .filter((id): id is string => id !== undefined);

      await pb.collection('topics').update(topicId, {
        related_topics: resolve(topic.relationships.related),
        prerequisite_topics: resolve(topic.relationships.prerequisites),
        contrast_topics: resolve(topic.relationships.contrasts),
      });
    }
  }

  return writtenTopics;
}

export async function updateTopicQdrantIds(
  topicId: string,
  qdrantChunkIds: string[],
): Promise<void> {
  const pb = await getPocketBase();
  await pb.collection('topics').update(topicId, { qdrant_chunk_ids: qdrantChunkIds });
}

export async function markDocumentFailed(documentId: string, reason: string): Promise<void> {
  console.error(`[write] document ${documentId} failed: ${reason}`);
  const pb = await getPocketBase();
  await pb.collection('source_documents').update(documentId, { status: 'failed' });
}
