#!/usr/bin/env node
/**
 * Script d'import COMPLET des documents Markdown dans Memento
 * Les notes sont créées avec isMarkdown: true
 */

import { PrismaClient } from '@prisma/client';
import { readFileSync } from 'fs';
import { join } from 'path';

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

// Liste des documents
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 des documents Markdown dans Memento...\n');

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

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

  if (!notebook) {
    console.log('❌ Notebook "Documentation" non trouvé');
    process.exit(1);
  }

  console.log('📁 Notebook "Documentation" trouvé\n');

  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;
      }

      // Chercher la note existante
      const existing = await prisma.note.findFirst({
        where: {
          title: doc.title,
          notebookId: notebook.id,
        },
      });

      if (existing) {
        // Mettre à jour avec isMarkdown: true
        await prisma.note.update({
          where: { id: existing.id },
          data: {
            content: content,
            color: doc.color,
            labels: JSON.stringify(['documentation']),
            isMarkdown: true,  // ✅ FORMAT MARKDOWN ACTIVÉ
            updatedAt: new Date(),
          },
        });
        console.log(`🔄 Mis à jour (Markdown): ${doc.title}`);
        updated++;
      } else {
        console.log(`⚠️  Note non trouvée: ${doc.title}`);
      }
    } catch (error) {
      console.log(`❌ Erreur ${doc.title}: ${error.message}`);
      errors++;
    }
  }

  console.log(`\n📊 Résumé:`);
  console.log(`   Mis à jour en Markdown: ${updated}`);
  console.log(`   Erreurs: ${errors}`);
  console.log(`\n✨ Toutes les notes sont maintenant en format Markdown !`);
}

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