// DBIS Conscious-Ledger Integration Model - Cognitive Smart Contract Service
// Executes contracts based on cognitive alignment

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { climIntegrationService } from './clim-integration.service';


export interface CognitiveContractRequest {
  contractId: string;
  stateId: string;
  threshold: number;
  action: string;
  parameters?: Record<string, unknown>;
}

export interface ContractExecutionResult {
  executed: boolean;
  cognitiveAlignment: number;
  action: string;
  reason: string;
}

export class ClimContractService {
  /**
   * Evaluate cognitive alignment and execute contract
   * if cognitive_alignment > threshold: execute_contract()
   * else: delay_or_reject()
   */
  async evaluateCognitiveAlignment(stateId: string, threshold: number = 0.7): Promise<ContractExecutionResult> {
    const state = await prisma.consciousness_states.findUnique({
      where: { stateId },
    });

    if (!state) {
      throw new Error(`Consciousness state not found: ${stateId}`);
    }

    // Cognitive alignment is based on influence level and state consistency
    const cognitiveAlignment = state.influenceLevel;

    if (cognitiveAlignment > threshold) {
      return {
        executed: true,
        cognitiveAlignment,
        action: 'execute',
        reason: 'Cognitive alignment exceeds threshold',
      };
    } else {
      return {
        executed: false,
        cognitiveAlignment,
        action: 'delay',
        reason: 'Cognitive alignment below threshold',
      };
    }
  }

  /**
   * Create cognitive smart contract
   */
  async createCognitiveContract(request: CognitiveContractRequest) {
    const contractId = `CLIM-CONTRACT-${uuidv4()}`;

    // Verify state exists
    const state = await prisma.consciousness_states.findUnique({
      where: { stateId: request.stateId },
    });

    if (!state) {
      throw new Error(`Consciousness state not found: ${request.stateId}`);
    }

    // Evaluate alignment
    const alignment = await this.evaluateCognitiveAlignment(request.stateId, request.threshold);

    const contract = await prisma.cognitive_contracts.create({
      data: {
        contractId,
        stateId: request.stateId,
        threshold: request.threshold,
        action: request.action,
        parameters: request.parameters || {},
        cognitiveAlignment: alignment.cognitiveAlignment,
        executionStatus: alignment.executed ? 'pending_execution' : 'delayed',
        status: 'active',
      },
    });

    return contract;
  }

  /**
   * Execute cognitive contract
   */
  async executeCognitiveContract(contractId: string): Promise<ContractExecutionResult> {
    const contract = await prisma.cognitive_contracts.findUnique({
      where: { contractId },
      include: {
        state: true,
      },
    });

    if (!contract) {
      throw new Error(`Contract not found: ${contractId}`);
    }

    // Re-evaluate alignment
    const alignment = await this.evaluateCognitiveAlignment(contract.stateId, contract.threshold);

    if (alignment.executed) {
      // Update contract status
      await prisma.cognitive_contracts.update({
        where: { contractId },
        data: {
          executionStatus: 'executed',
          executedAt: new Date(),
          updatedAt: new Date(),
        },
      });

      return {
        executed: true,
        cognitiveAlignment: alignment.cognitiveAlignment,
        action: contract.action,
        reason: 'Contract executed successfully',
      };
    } else {
      // Delay execution
      await prisma.cognitive_contracts.update({
        where: { contractId },
        data: {
          executionStatus: 'delayed',
          updatedAt: new Date(),
        },
      });

      return {
        executed: false,
        cognitiveAlignment: alignment.cognitiveAlignment,
        action: contract.action,
        reason: alignment.reason,
      };
    }
  }

  /**
   * Get contract by ID
   */
  async getContract(contractId: string) {
    return await prisma.cognitive_contracts.findUnique({
      where: { contractId },
      include: {
        state: true,
      },
    });
  }

  /**
   * Get contracts for state
   */
  async getContractsForState(stateId: string) {
    return await prisma.cognitive_contracts.findMany({
      where: { stateId },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Get pending execution contracts
   */
  async getPendingExecutionContracts() {
    return await prisma.cognitive_contracts.findMany({
      where: {
        executionStatus: 'pending_execution',
        status: 'active',
      },
      orderBy: { createdAt: 'asc' },
    });
  }
}

export const climContractService = new ClimContractService();

