import { addConversation, addMessage, listConversations } from './db';
import type { Conversation, Message } from './types';

interface InferenceLogItem {
  prompt?: string;
  response?: string;
  model?: string;
  timestamp?: number;
}

interface ChatItem {
  role?: 'user' | 'assistant';
  content?: string;
}

export async function migrateV3ToV4(): Promise<{
  migrated: boolean;
  stats: { conversations: number; messages: number };
}> {
  if (typeof window === 'undefined') {
    return { migrated: false, stats: { conversations: 0, messages: 0 } };
  }

  const already = localStorage.getItem('llm-migrated-v4');
  if (already === 'true') {
    return { migrated: false, stats: { conversations: 0, messages: 0 } };
  }

  // Guard against duplicate migrations if db already has records
  const existing = await listConversations({ limit: 1 });
  if (existing.length > 0) {
    localStorage.setItem('llm-migrated-v4', 'true');
    return { migrated: false, stats: { conversations: 0, messages: 0 } };
  }

  let conversations = 0;
  let messages = 0;

  const inferenceRaw = localStorage.getItem('llm-inference-log');
  if (inferenceRaw) {
    try {
      const entries = JSON.parse(inferenceRaw) as InferenceLogItem[];
      for (const entry of entries) {
        const prompt = String(entry.prompt || '').trim();
        const response = String(entry.response || '').trim();
        if (!prompt && !response) continue;

        const now = Number(entry.timestamp || Date.now());
        const convId = crypto.randomUUID();
        const conv: Conversation = {
          id: convId,
          title: prompt ? prompt.split(/\s+/).slice(0, 5).join(' ') : 'Migrated Conversation',
          model: entry.model || '',
          messageCount: 0,
          createdAt: now,
          updatedAt: now,
          pinned: false,
          archived: false,
          metadata: {
            totalTokens: 0,
            totalPrompts: prompt ? 1 : 0,
            avgTokPerSec: 0,
            models: entry.model ? [entry.model] : [],
          },
        };
        await addConversation(conv);
        conversations += 1;

        const rows: Message[] = [];
        if (prompt) {
          rows.push({
            id: crypto.randomUUID(),
            conversationId: convId,
            role: 'user',
            content: prompt,
            timestamp: now,
            model: entry.model || '',
          });
        }
        if (response) {
          rows.push({
            id: crypto.randomUUID(),
            conversationId: convId,
            role: 'assistant',
            content: response,
            timestamp: now + 1,
            model: entry.model || '',
          });
        }

        for (const row of rows) {
          await addMessage(row);
          messages += 1;
        }
      }
    } catch {
      // Ignore malformed migration payload
    }
  }

  for (const key of Object.keys(localStorage)) {
    if (!key.startsWith('llm-chat-')) continue;
    const model = key.replace('llm-chat-', '');
    const raw = localStorage.getItem(key);
    if (!raw) continue;

    try {
      const chat = JSON.parse(raw) as ChatItem[];
      if (!Array.isArray(chat) || chat.length === 0) continue;

      const now = Date.now();
      const convId = crypto.randomUUID();
      const conv: Conversation = {
        id: convId,
        title: `Chat (${model})`,
        model,
        messageCount: chat.length,
        createdAt: now,
        updatedAt: now,
        pinned: false,
        archived: false,
        metadata: {
          totalTokens: 0,
          totalPrompts: chat.filter(item => item.role === 'user').length,
          avgTokPerSec: 0,
          models: model ? [model] : [],
        },
      };
      await addConversation(conv);
      conversations += 1;

      let ts = now;
      for (const item of chat) {
        if (!item.content) continue;
        const msg: Message = {
          id: crypto.randomUUID(),
          conversationId: convId,
          role: item.role === 'assistant' ? 'assistant' : 'user',
          content: item.content,
          timestamp: ts,
          model,
        };
        ts += 1;
        await addMessage(msg);
        messages += 1;
      }
    } catch {
      // Ignore malformed chat payload
    }
  }

  localStorage.setItem('llm-migrated-v4', 'true');

  return {
    migrated: conversations > 0 || messages > 0,
    stats: { conversations, messages },
  };
}
