#!/usr/bin/env node
/**
 * Create columns in ai_data_Memory table via NocoDB API
 */

const axios = require('axios');

const NOCODB_URL = 'http://192.168.25.5:8080';
const TABLE_ID = 'mx149yctebfwvys';

// Get token from vault
async function getVaultToken() {
  const vaultResp = await axios.post('https://beavault.beawit.net:8200/v1/auth/approle/login', {
    role_id: '75d2dcfb-9c65-7f60-59b4-eee8c7f8dc0e',
    secret_id: '6202b465-2f25-547c-ec07-f47cfc4dda3e'
  }, { httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }) });
  
  return vaultResp.data.auth.client_token;
}

async function getNocoDBToken(vaultToken) {
  const resp = await axios.get('https://beavault.beawit.net:8200/v1/kv/data/api/infrastructure', {
    headers: { 'X-Vault-Token': vaultToken },
    httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false })
  });
  
  return resp.data.data.data['nocodb-token'];
}

async function createColumn(token, columnDef) {
  try {
    const response = await axios.post(
      `${NOCODB_URL}/api/v2/meta/tables/${TABLE_ID}/columns`,
      columnDef,
      {
        headers: {
          'xc-token': token,
          'Content-Type': 'application/json'
        }
      }
    );
    console.log(`✅ Created: ${columnDef.title}`);
    return response.data;
  } catch (err) {
    if (err.response?.data?.msg?.includes('already exists')) {
      console.log(`⚠️ Already exists: ${columnDef.title}`);
    } else {
      console.log(`❌ Failed: ${columnDef.title} - ${err.response?.data?.msg || err.message}`);
    }
  }
}

async function main() {
  console.log('=== Creating columns in ai_data_Memory ===\n');
  
  const vaultToken = await getVaultToken();
  const nocodbToken = await getNocoDBToken(vaultToken);
  
  console.log('Got tokens, creating columns...\n');
  
  // Core columns for all record types
  const columns = [
    // Type discriminator
    { title: 'type', column_name: 'type', uidt: 'SingleSelect', dtxp: 'correction,preference,episode,decision,validation' },
    
    // Correction fields
    { title: 'pattern', column_name: 'pattern', uidt: 'LongText' },
    { title: 'exclude_pattern', column_name: 'exclude_pattern', uidt: 'LongText' },
    { title: 'severity', column_name: 'severity', uidt: 'SingleSelect', dtxp: 'error,warning,auto-correct' },
    { title: 'message', column_name: 'message', uidt: 'LongText' },
    { title: 'suggestion', column_name: 'suggestion', uidt: 'LongText' },
    { title: 'blocking', column_name: 'blocking', uidt: 'Checkbox' },
    { title: 'auto_detected', column_name: 'auto_detected', uidt: 'Checkbox' },
    { title: 'manual_entry', column_name: 'manual_entry', uidt: 'Checkbox' },
    { title: 'hit_count', column_name: 'hit_count', uidt: 'Number' },
    { title: 'last_triggered', column_name: 'last_triggered', uidt: 'DateTime' },
    
    // Preference fields
    { title: 'category', column_name: 'category', uidt: 'SingleLineText' },
    { title: 'key', column_name: 'key', uidt: 'SingleLineText' },
    { title: 'value', column_name: 'value', uidt: 'LongText' },
    { title: 'importance', column_name: 'importance', uidt: 'Number' },
    { title: 'confidence', column_name: 'confidence', uidt: 'Decimal' },
    { title: 'tags', column_name: 'tags', uidt: 'LongText' },
    { title: 'access_count', column_name: 'access_count', uidt: 'Number' },
    { title: 'last_accessed', column_name: 'last_accessed', uidt: 'DateTime' },
    { title: 'confirmed_count', column_name: 'confirmed_count', uidt: 'Number' },
    
    // Episode fields
    { title: 'date', column_name: 'date', uidt: 'Date' },
    { title: 'summary', column_name: 'summary', uidt: 'LongText' },
    { title: 'details', column_name: 'details', uidt: 'LongText' },
    { title: 'project', column_name: 'project', uidt: 'SingleLineText' },
    { title: 'outcomes', column_name: 'outcomes', uidt: 'LongText' },
    { title: 'corrections_triggered', column_name: 'corrections_triggered', uidt: 'LongText' },
    
    // Decision fields
    { title: 'decision', column_name: 'decision', uidt: 'LongText' },
    { title: 'alternatives', column_name: 'alternatives', uidt: 'LongText' },
    { title: 'rationale', column_name: 'rationale', uidt: 'LongText' },
    { title: 'status', column_name: 'status', uidt: 'SingleSelect', dtxp: 'active,reversed,deprecated' },
    { title: 'reversed_by', column_name: 'reversed_by', uidt: 'SingleLineText' },
    
    // Validation fields
    { title: 'session_id', column_name: 'session_id', uidt: 'SingleLineText' },
    { title: 'input_length', column_name: 'input_length', uidt: 'Number' },
    { title: 'output_length', column_name: 'output_length', uidt: 'Number' },
    { title: 'violations_found', column_name: 'violations_found', uidt: 'Number' },
    { title: 'new_patterns_detected', column_name: 'new_patterns_detected', uidt: 'Number' },
    { title: 'corrections_auto_stored', column_name: 'corrections_auto_stored', uidt: 'Number' },
    { title: 'processing_time_ms', column_name: 'processing_time_ms', uidt: 'Number' },
    { title: 'workflow', column_name: 'workflow', uidt: 'SingleLineText' },
    
    // Timestamps
    { title: 'created_at', column_name: 'created_at', uidt: 'DateTime' },
    { title: 'updated_at', column_name: 'updated_at', uidt: 'DateTime' }
  ];
  
  for (const col of columns) {
    await createColumn(nocodbToken, col);
  }
  
  console.log('\n=== Column creation complete ===');
}

main().catch(err => {
  console.error('Error:', err);
  process.exit(1);
});
