#!/usr/bin/env node
/**
 * Script d'import COMPLET des documents dans Memento
 * Importe le contenu intégral de chaque fichier .md
 */

import { PrismaClient } from '@prisma/client';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const prisma = new PrismaClient({
  datasources: {
    db: { url: 'file:/Users/sepehr/dev/Keep/memento-note/prisma/dev.db' },
  },
});

// Liste des documents avec leurs chemins
const documents = [
  { file: 'guide-utilisateur-mcp.md', title: '📘 Guide Utilisateur MCP', color: 'blue' },
  { file: 'source-tree-analysis.md', title: '📁 Source Tree Analysis', color: 'green' },
  { file: 'project-overview.md', title: '🎯 Project Overview', color: 'purple' },
  { file: 'deployment-guide.md', title: '🚀 Deployment Guide', color: 'orange' },
  { file: 'development-guide-memento-note.md', title: '💻 Development Guide', color: 'teal' },
  { file: 'integration-architecture.md', title: '🔌 Integration Architecture', color: 'blue' },
  { file: 'api-contracts-memento-note.md', title: '📡 API Contracts Keep Notes', color: 'yellow' },
  { file: 'architecture-memento-note.md', title: '🏗️ Architecture Keep Notes', color: 'purple' },
  { file: 'code-review-cleanup-report.md', title: '🔍 Code Review Cleanup Report', color: 'red' },
  { file: 'data-models.md', title: '🗄️ Data Models', color: 'gray' },
  { file: 'component-inventory.md', title: '🧩 Component Inventory', color: 'teal' },
  { file: 'architecture-mcp-server.md', title: '🔧 Architecture MCP Server', color: 'blue' },
  { file: 'api-contracts-mcp-server.md', title: '📋 API Contracts MCP Server', color: 'yellow' },
  { file: 'monetization-analysis.md', title: '💰 Monetization Analysis', color: 'green' },
  { file: 'index.md', title: '📚 Index Documentation', color: 'gray' },
  { file: 'mcp-optimization-report.md', title: '⚡ MCP Optimization Report', color: 'purple' },
];

async function importDocuments() {
  console.log('📝 Import COMPLET des documents dans Memento...\n');

  // Trouver le user
  let user = await prisma.user.findFirst();
  if (!user) {
    console.log('❌ Aucun utilisateur trouvé');
    process.exit(1);
  }

  // Trouver ou créer le notebook "Documentation"
  let notebook = await prisma.notebook.findFirst({
    where: { name: 'Documentation' },
  });

  if (!notebook) {
    const highestOrder = await prisma.notebook.findFirst({
      orderBy: { order: 'desc' },
      select: { order: true },
    });
    
    notebook = await prisma.notebook.create({
      data: {
        name: 'Documentation',
        icon: '📚',
        color: '#3B82F6',
        order: (highestOrder?.order ?? -1) + 1,
        userId: user.id,
      },
    });
    console.log('📁 Notebook "Documentation" créé\n');
  } else {
    console.log('📁 Notebook "Documentation" trouvé\n');
  }

  let created = 0;
  let updated = 0;
  let errors = 0;

  for (const doc of documents) {
    try {
      const filePath = join('/Users/sepehr/dev/Keep/docs', doc.file);
      let content;
      
      try {
        content = readFileSync(filePath, 'utf-8');
      } catch (e) {
        console.log(`⚠️  Fichier non trouvé: ${doc.file}`);
        errors++;
        continue;
      }

      // Vérifier si la note existe déjà
      const existing = await prisma.note.findFirst({
        where: {
          title: doc.title,
          notebookId: notebook.id,
        },
      });

      if (existing) {
        // Mettre à jour avec le contenu complet
        await prisma.note.update({
          where: { id: existing.id },
          data: {
            content: content,
            color: doc.color,
            labels: JSON.stringify(['documentation']),
            updatedAt: new Date(),
          },
        });
        console.log(`🔄 Mis à jour: ${doc.title} (${content.length} caractères)`);
        updated++;
      } else {
        // Créer nouvelle note
        await prisma.note.create({
          data: {
            title: doc.title,
            content: content,
            color: doc.color,
            labels: JSON.stringify(['documentation']),
            notebookId: notebook.id,
            userId: user.id,
            type: 'text',
            isPinned: false,
            isArchived: false,
          },
        });
        console.log(`✅ Créé: ${doc.title} (${content.length} caractères)`);
        created++;
      }
    } catch (error) {
      console.log(`❌ Erreur ${doc.title}: ${error.message}`);
      errors++;
    }
  }

  console.log(`\n📊 Résumé:`);
  console.log(`   Créés: ${created}`);
  console.log(`   Mis à jour: ${updated}`);
  console.log(`   Erreurs: ${errors}`);
  console.log(`   Total: ${documents.length}`);
  console.log(`\n✨ Import terminé !`);
}

importDocuments()
  .catch(console.error)
  .finally(() => prisma.$disconnect());
