// DBIS Supra-Constitutional Charter Service
// Charter articles and principles enforcement

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';


export interface CreateCharterRequest {
  version: string;
  effectiveDate?: Date;
}

export interface CreateArticleRequest {
  charterId: string;
  articleNumber: number;
  title: string;
  content: string;
  principleType?: string;
  enforcementLevel?: string;
}

export class ScdcCharterService {
  /**
   * Create or update Supra-Constitutional Charter
   */
  async createCharter(request: CreateCharterRequest) {
    const charterId = `SCDC-${uuidv4()}`;

    // Archive previous active charter if exists
    await prisma.supraConstitutionalCharter.updateMany({
      where: { status: 'active' },
      data: { status: 'superseded' },
    });

    const charter = await prisma.supraConstitutionalCharter.create({
      data: {
        charterId,
        version: request.version,
        effectiveDate: request.effectiveDate || new Date(),
        status: 'active',
        metaSovereignPrimacy: true,
        dimensionalConsistency: true,
        temporalNonContradiction: true,
        economicCausality: true,
      },
    });

    return charter;
  }

  /**
   * Get active charter
   */
  async getActiveCharter() {
    return await prisma.supraConstitutionalCharter.findFirst({
      where: { status: 'active' },
      include: {
        articles: true,
        integrityChecks: {
          orderBy: { createdAt: 'desc' },
          take: 10,
        },
        aiActions: {
          orderBy: { createdAt: 'desc' },
          take: 10,
        },
      },
    });
  }

  /**
   * Get charter by ID
   */
  async getCharter(charterId: string) {
    return await prisma.supraConstitutionalCharter.findUnique({
      where: { charterId },
      include: {
        articles: true,
        integrityChecks: true,
        aiActions: true,
      },
    });
  }

  /**
   * Create charter article
   */
  async createArticle(request: CreateArticleRequest) {
    const articleId = `SCDC-ARTICLE-${uuidv4()}`;

    const article = await prisma.charterArticle.create({
      data: {
        articleId,
        charterId: request.charterId,
        articleNumber: request.articleNumber,
        title: request.title,
        content: request.content,
        principleType: request.principleType || null,
        enforcementLevel: request.enforcementLevel || 'mandatory',
        status: 'active',
      },
    });

    return article;
  }

  /**
   * Get article by number
   */
  async getArticle(charterId: string, articleNumber: number) {
    return await prisma.charterArticle.findFirst({
      where: {
        charterId,
        articleNumber,
        status: 'active',
      },
    });
  }

  /**
   * Get all articles for a charter
   */
  async getArticles(charterId: string) {
    return await prisma.charterArticle.findMany({
      where: {
        charterId,
        status: 'active',
      },
      orderBy: { articleNumber: 'asc' },
    });
  }

  /**
   * Verify principle compliance
   */
  async verifyPrinciple(principleType: string): Promise<boolean> {
    const charter = await this.getActiveCharter();
    if (!charter) {
      return false;
    }

    switch (principleType) {
      case 'meta_sovereign_primacy':
        return charter.metaSovereignPrimacy;
      case 'dimensional_consistency':
        return charter.dimensionalConsistency;
      case 'temporal_non_contradiction':
        return charter.temporalNonContradiction;
      case 'economic_causality':
        return charter.economicCausality;
      default:
        return false;
    }
  }
}

export const scdcCharterService = new ScdcCharterService();

