// DBIS Supra-Constitutional AI Mandate Service
// Autonomous AI enforcement (Article 22: NCE, ARI, SARE)

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { scdcCharterService } from './scdc-charter.service';


export type AISystem = 'NCE' | 'ARI' | 'SARE';

export interface CreateAIActionRequest {
  aiSystem: AISystem;
  actionType: string;
  actionDetails: Record<string, unknown>;
  authorizationLevel: 'autonomous' | 'supervised' | 'manual';
}

export class ScdcAIMandateService {
  /**
   * Create autonomous AI action (Article 22)
   * DBIS AI may enforce stability autonomously
   */
  async createAIAction(request: CreateAIActionRequest) {
    const charter = await scdcCharterService.getActiveCharter();
    if (!charter) {
      throw new Error('No active charter found');
    }

    // Verify Article 22 exists
    const article22 = await scdcCharterService.getArticle(charter.charterId, 22);
    if (!article22 || article22.principleType !== 'ai_mandate') {
      throw new Error('Article 22 (Autonomous AI Mandate) not found');
    }

    const actionId = `AIA-${uuidv4()}`;

    const action = await prisma.aiAutonomousAction.create({
      data: {
        actionId,
        charterId: charter.charterId,
        aiSystem: request.aiSystem,
        actionType: request.actionType,
        actionDetails: request.actionDetails,
        authorizationLevel: request.authorizationLevel,
        status: 'pending',
      },
    });

    // If autonomous, execute immediately
    if (request.authorizationLevel === 'autonomous') {
      await this.executeAction(actionId);
    }

    return action;
  }

  /**
   * Execute AI action
   */
  async executeAction(actionId: string) {
    const action = await prisma.aiAutonomousAction.findUnique({
      where: { actionId },
    });

    if (!action) {
      throw new Error(`Action not found: ${actionId}`);
    }

    if (action.status !== 'pending') {
      throw new Error(`Action already ${action.status}`);
    }

    // Update status to executing
    await prisma.aiAutonomousAction.update({
      where: { actionId },
      data: {
        status: 'executing',
      },
    });

    try {
      // In production, this would:
      // - Route to appropriate AI system (NCE, ARI, SARE)
      // - Execute the action
      // - Handle results

      // Simulate execution
      await new Promise((resolve) => setTimeout(resolve, 100));

      // Mark as completed
      await prisma.aiAutonomousAction.update({
        where: { actionId },
        data: {
          status: 'completed',
          executedAt: new Date(),
        },
      });
    } catch (error) {
      await prisma.aiAutonomousAction.update({
        where: { actionId },
        data: {
          status: 'failed',
        },
      });
      throw error;
    }
  }

  /**
   * Get AI actions by system
   */
  async getActionsBySystem(aiSystem: AISystem, limit = 50) {
    return await prisma.aiAutonomousAction.findMany({
      where: { aiSystem },
      orderBy: { createdAt: 'desc' },
      take: limit,
    });
  }

  /**
   * Get AI actions by type
   */
  async getActionsByType(actionType: string, limit = 50) {
    return await prisma.aiAutonomousAction.findMany({
      where: { actionType },
      orderBy: { createdAt: 'desc' },
      take: limit,
    });
  }

  /**
   * Get pending autonomous actions
   */
  async getPendingAutonomousActions() {
    return await prisma.aiAutonomousAction.findMany({
      where: {
        authorizationLevel: 'autonomous',
        status: 'pending',
      },
      orderBy: { createdAt: 'asc' },
    });
  }

  /**
   * Verify AI system has mandate
   */
  async verifyAIMandate(aiSystem: AISystem): Promise<boolean> {
    const charter = await scdcCharterService.getActiveCharter();
    if (!charter) {
      return false;
    }

    const article22 = await scdcCharterService.getArticle(charter.charterId, 22);
    if (!article22) {
      return false;
    }

    // Verify AI system is authorized
    const authorizedSystems: AISystem[] = ['NCE', 'ARI', 'SARE'];
    return authorizedSystems.includes(aiSystem);
  }
}

export const scdcAIMandateService = new ScdcAIMandateService();

