#!/usr/bin/env node
/**
 * Add API Reference documentation to database
 *
 * Creates document entries for:
 * - API Reference HTML page (links to the page)
 * - JavaScript Code Examples (markdown content)
 * - Python Code Examples (markdown content)
 * - OpenAPI Specification (download link)
 */

// Load environment variables
require('dotenv').config();

const fs = require('fs');
const path = require('path');
const { getDb } = require('../src/utils/db.util');
const { marked } = require('marked');

async function addApiDocs() {
  console.log('📝 Adding API documentation to database...\n');

  const db = await getDb();
  const collection = db.collection('documents');

  const docs = [
    // 1. API Reference HTML Page
    {
      title: 'API Reference: Complete Endpoint Documentation',
      slug: 'api-reference-complete',
      quadrant: null,
      persistence: 'HIGH',
      audience: 'implementer',
      visibility: 'public',
      category: 'technical-reference',
      order: 10,
      content_markdown: `# API Reference: Complete Endpoint Documentation

Complete REST API reference for the Tractatus Framework with all endpoints, request/response examples, and authentication details.

**View Online:** [API Reference Page](/api-reference.html)

## What's Included

- **Authentication** - JWT-based authentication flow
- **Documents API** - List, search, create, update documents
- **Governance Services** - All 6 core services:
  - InstructionPersistenceClassifier
  - CrossReferenceValidator
  - BoundaryEnforcer
  - ContextPressureMonitor
  - MetacognitiveVerifier
  - AuditLogger
- **Admin Endpoints** - Moderation queue, system stats, activity logs
- **Error Codes** - Complete error reference with examples

## Quick Links

- [View API Reference](/api-reference.html)
- [Download OpenAPI Specification](/docs/api/openapi.yaml)
- [JavaScript Examples](/docs/api/examples-javascript.md)
- [Python Examples](/docs/api/examples-python.md)

## Key Features

✅ Complete request/response schemas
✅ Authentication workflows
✅ Rate limiting documentation
✅ Error handling patterns
✅ Lookup tables for enums
✅ OpenAPI 3.0 specification
`,
      content_html: null, // Will be generated from markdown
      toc: [],
      metadata: {
        author: 'John Stroh',
        date_created: new Date(),
        date_updated: new Date(),
        version: '1.0',
        document_code: 'API-REF-001',
        related_documents: ['api-js-examples', 'api-py-examples', 'openapi-spec'],
        tags: ['api', 'rest', 'endpoints', 'reference', 'openapi']
      }
    },

    // 2. JavaScript Code Examples
    {
      title: 'JavaScript API Integration Examples',
      slug: 'api-javascript-examples',
      quadrant: null,
      persistence: 'HIGH',
      audience: 'technical',
      visibility: 'public',
      category: 'technical-reference',
      order: 11,
      content_markdown: fs.readFileSync(
        path.join(__dirname, '../docs/api/examples-javascript.md'),
        'utf8'
      ),
      content_html: null, // Will be generated
      toc: [],
      metadata: {
        author: 'John Stroh',
        date_created: new Date(),
        date_updated: new Date(),
        version: '1.0',
        document_code: 'API-JS-001',
        related_documents: ['api-reference-complete', 'api-py-examples'],
        tags: ['api', 'javascript', 'nodejs', 'code-examples', 'integration']
      },
      download_formats: {
        markdown: '/docs/api/examples-javascript.md'
      }
    },

    // 3. Python Code Examples
    {
      title: 'Python API Integration Examples',
      slug: 'api-python-examples',
      quadrant: null,
      persistence: 'HIGH',
      audience: 'technical',
      visibility: 'public',
      category: 'technical-reference',
      order: 12,
      content_markdown: fs.readFileSync(
        path.join(__dirname, '../docs/api/examples-python.md'),
        'utf8'
      ),
      content_html: null, // Will be generated
      toc: [],
      metadata: {
        author: 'John Stroh',
        date_created: new Date(),
        date_updated: new Date(),
        version: '1.0',
        document_code: 'API-PY-001',
        related_documents: ['api-reference-complete', 'api-js-examples'],
        tags: ['api', 'python', 'requests', 'code-examples', 'integration']
      },
      download_formats: {
        markdown: '/docs/api/examples-python.md'
      }
    },

    // 4. OpenAPI Specification
    {
      title: 'OpenAPI 3.0 Specification',
      slug: 'openapi-specification',
      quadrant: null,
      persistence: 'HIGH',
      audience: 'technical',
      visibility: 'public',
      category: 'technical-reference',
      order: 13,
      content_markdown: `# OpenAPI 3.0 Specification

Complete OpenAPI 3.0 specification for the Tractatus Framework REST API.

**Download:** [openapi.yaml](/docs/api/openapi.yaml)

## What is OpenAPI?

OpenAPI is a standard format for describing REST APIs. The specification can be used to:

- Generate interactive API documentation (Swagger UI, Redoc)
- Auto-generate client SDKs in multiple languages
- Validate API requests and responses
- Mock API servers for testing
- Import into tools like Postman, Insomnia

## Our Specification

📄 **File:** \`openapi.yaml\` (1,621 lines, 46KB)

**Includes:**
- All authentication endpoints
- Document management endpoints
- All 6 governance service endpoints
- Audit logging endpoints
- Admin endpoints
- Complete request/response schemas
- Security definitions (JWT Bearer)
- Error responses
- Rate limiting details

## How to Use

### With Swagger UI

\`\`\`bash
# Using npx
npx swagger-ui-dist -u /docs/api/openapi.yaml

# Or with Docker
docker run -p 8080:8080 \\
  -e SWAGGER_JSON=/docs/openapi.yaml \\
  swaggerapi/swagger-ui
\`\`\`

### With Postman

1. Open Postman
2. Import → Link
3. Enter: https://agenticgovernance.digital/docs/api/openapi.yaml
4. All endpoints will be imported with examples

### Generate Client SDK

\`\`\`bash
# Python client
openapi-generator generate \\
  -i /docs/api/openapi.yaml \\
  -g python \\
  -o ./tractatus-client-python

# TypeScript client
openapi-generator generate \\
  -i /docs/api/openapi.yaml \\
  -g typescript-axios \\
  -o ./tractatus-client-ts
\`\`\`

## Related Documentation

- [API Reference](/api-reference.html) - Human-readable documentation
- [JavaScript Examples](/docs/api/examples-javascript.md)
- [Python Examples](/docs/api/examples-python.md)
`,
      content_html: null,
      toc: [],
      metadata: {
        author: 'John Stroh',
        date_created: new Date(),
        date_updated: new Date(),
        version: '1.0',
        document_code: 'API-SPEC-001',
        related_documents: ['api-reference-complete', 'api-js-examples', 'api-py-examples'],
        tags: ['api', 'openapi', 'swagger', 'specification', 'yaml']
      },
      download_formats: {
        yaml: '/docs/api/openapi.yaml'
      }
    }
  ];

  let added = 0;
  let skipped = 0;
  let errors = 0;

  for (const doc of docs) {
    try {
      // Check if document already exists
      const existing = await collection.findOne({ slug: doc.slug });

      if (existing) {
        console.log(`⏭️  Skipped (already exists): "${doc.title}"`);
        skipped++;
        continue;
      }

      // Generate HTML from markdown if not provided
      if (!doc.content_html && doc.content_markdown) {
        doc.content_html = marked.parse(doc.content_markdown);
      }

      // Insert document
      await collection.insertOne(doc);
      console.log(`✅ Added: "${doc.title}"`);
      console.log(`   Category: ${doc.category}`);
      console.log(`   Audience: ${doc.audience}`);
      console.log(`   Order: ${doc.order}\n`);
      added++;

    } catch (error) {
      console.error(`❌ Error adding "${doc.title}":`, error.message);
      errors++;
    }
  }

  console.log('\n' + '='.repeat(60));
  console.log('📊 Summary:');
  console.log('='.repeat(60));
  console.log(`✅ Added: ${added}`);
  console.log(`⏭️  Skipped: ${skipped}`);
  console.log(`❌ Errors: ${errors}`);
  console.log('='.repeat(60));

  process.exit(0);
}

// Run script
addApiDocs().catch(error => {
  console.error('❌ Script failed:', error);
  process.exit(1);
});
