-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";

-- CreateTable
CREATE TABLE "users" (
    "id" TEXT NOT NULL,
    "email" TEXT NOT NULL,
    "passwordHash" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "employeeId" TEXT NOT NULL,
    "department" TEXT NOT NULL,
    "departmentAr" TEXT NOT NULL,
    "phone" TEXT,
    "locale" TEXT NOT NULL DEFAULT 'ar',
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "lastLoginAt" TIMESTAMP(3),
    "failedLoginCount" INTEGER NOT NULL DEFAULT 0,
    "lockedUntil" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "roles" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "level" INTEGER NOT NULL DEFAULT 10,
    "isSystem" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "roles_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "permissions" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "resource" TEXT NOT NULL,
    "action" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "permissions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "role_permissions" (
    "id" TEXT NOT NULL,
    "roleId" TEXT NOT NULL,
    "permissionId" TEXT NOT NULL,
    "grantedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "role_permissions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "user_roles" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "roleId" TEXT NOT NULL,
    "assignedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "assignedBy" TEXT,

    CONSTRAINT "user_roles_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "sessions" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "tokenId" TEXT NOT NULL,
    "ip" TEXT,
    "userAgent" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "expiresAt" TIMESTAMP(3) NOT NULL,
    "revokedAt" TIMESTAMP(3),

    CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "audit_logs" (
    "id" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "userId" TEXT,
    "userEmail" TEXT NOT NULL,
    "userRole" TEXT NOT NULL,
    "action" TEXT NOT NULL,
    "entity" TEXT NOT NULL,
    "entityId" TEXT,
    "ip" TEXT,
    "userAgent" TEXT,
    "beforeJson" TEXT,
    "afterJson" TEXT,
    "status" TEXT NOT NULL DEFAULT 'success',
    "detail" TEXT,

    CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "regions" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "lat" DOUBLE PRECISION NOT NULL,
    "lon" DOUBLE PRECISION NOT NULL,
    "populationK" INTEGER NOT NULL,
    "peakDemandMw" DOUBLE PRECISION NOT NULL,
    "capacityMw" DOUBLE PRECISION NOT NULL,
    "timezone" TEXT NOT NULL DEFAULT 'Asia/Riyadh',
    "climate" TEXT NOT NULL,
    "climateAr" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "regions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "sites" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "regionId" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "lat" DOUBLE PRECISION NOT NULL,
    "lon" DOUBLE PRECISION NOT NULL,
    "voltageLevelKv" DOUBLE PRECISION NOT NULL,
    "commissionedAt" TIMESTAMP(3) NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "sites_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "asset_types" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "category" TEXT NOT NULL,
    "icon" TEXT NOT NULL,
    "expectedLifeYears" INTEGER NOT NULL,
    "criticalityWeight" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "asset_types_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "assets" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "assetTypeId" TEXT NOT NULL,
    "siteId" TEXT NOT NULL,
    "regionId" TEXT NOT NULL,
    "lat" DOUBLE PRECISION NOT NULL,
    "lon" DOUBLE PRECISION NOT NULL,
    "capacityMw" DOUBLE PRECISION NOT NULL,
    "voltageKv" DOUBLE PRECISION NOT NULL,
    "ratedTempC" DOUBLE PRECISION NOT NULL DEFAULT 95,
    "coolingType" TEXT NOT NULL DEFAULT 'ONAN',
    "manufacturer" TEXT NOT NULL,
    "model" TEXT NOT NULL,
    "serialNumber" TEXT NOT NULL,
    "installedAt" TIMESTAMP(3) NOT NULL,
    "lastMaintenanceAt" TIMESTAMP(3),
    "nextMaintenanceAt" TIMESTAMP(3),
    "healthScore" DOUBLE PRECISION NOT NULL DEFAULT 90,
    "criticality" TEXT NOT NULL DEFAULT 'medium',
    "status" TEXT NOT NULL DEFAULT 'online',
    "customersServed" INTEGER NOT NULL DEFAULT 0,
    "seed" INTEGER NOT NULL,
    "profileKey" TEXT NOT NULL DEFAULT 'urban',
    "baselineLoadPct" DOUBLE PRECISION NOT NULL DEFAULT 62,
    "peakHour" INTEGER NOT NULL DEFAULT 15,
    "volatility" DOUBLE PRECISION NOT NULL DEFAULT 0.05,
    "agingFactor" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "isFlexibleLoad" BOOLEAN NOT NULL DEFAULT false,
    "hasBatterySupport" BOOLEAN NOT NULL DEFAULT false,
    "parentAssetId" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "assets_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "sensors" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetId" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "unit" TEXT NOT NULL,
    "minValue" DOUBLE PRECISION NOT NULL,
    "maxValue" DOUBLE PRECISION NOT NULL,
    "accuracy" DOUBLE PRECISION NOT NULL DEFAULT 0.5,
    "status" TEXT NOT NULL DEFAULT 'healthy',
    "firmware" TEXT NOT NULL DEFAULT '1.4.2',
    "lastSeenAt" TIMESTAMP(3),
    "installedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "lastCalibratedAt" TIMESTAMP(3),
    "samplingIntervalMin" INTEGER NOT NULL DEFAULT 15,

    CONSTRAINT "sensors_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "sensor_readings" (
    "id" TEXT NOT NULL,
    "sensorId" TEXT NOT NULL,
    "assetId" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL,
    "value" DOUBLE PRECISION NOT NULL,
    "quality" TEXT NOT NULL DEFAULT 'good',

    CONSTRAINT "sensor_readings_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "weather_data" (
    "id" TEXT NOT NULL,
    "regionId" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL,
    "tempC" DOUBLE PRECISION NOT NULL,
    "humidityPct" DOUBLE PRECISION NOT NULL,
    "windSpeedMs" DOUBLE PRECISION NOT NULL,
    "windDirDeg" DOUBLE PRECISION NOT NULL,
    "irradianceWm2" DOUBLE PRECISION NOT NULL,
    "cloudCoverPct" DOUBLE PRECISION NOT NULL,
    "dustIndex" DOUBLE PRECISION NOT NULL,
    "visibilityKm" DOUBLE PRECISION NOT NULL,
    "source" TEXT NOT NULL DEFAULT 'simulated',

    CONSTRAINT "weather_data_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "failure_patterns" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "eventType" TEXT NOT NULL,
    "severity" TEXT NOT NULL,
    "occurredAt" TIMESTAMP(3) NOT NULL,
    "regionId" TEXT,
    "assetId" TEXT,
    "assetTypeKey" TEXT NOT NULL,
    "durationMin" INTEGER NOT NULL,
    "customersAffect" INTEGER NOT NULL,
    "energyLostMwh" DOUBLE PRECISION NOT NULL,
    "outcome" TEXT NOT NULL,
    "outcomeAr" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "failure_patterns_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "failure_dna" (
    "id" TEXT NOT NULL,
    "patternId" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "version" TEXT NOT NULL DEFAULT 'dna-v1',
    "voltageDeviation" DOUBLE PRECISION NOT NULL,
    "frequencyDeviation" DOUBLE PRECISION NOT NULL,
    "loadPercentage" DOUBLE PRECISION NOT NULL,
    "temperature" DOUBLE PRECISION NOT NULL,
    "loadGrowthRate" DOUBLE PRECISION NOT NULL,
    "renewableVariability" DOUBLE PRECISION NOT NULL,
    "assetAge" DOUBLE PRECISION NOT NULL,
    "maintenanceScore" DOUBLE PRECISION NOT NULL,
    "neighboringFailures" DOUBLE PRECISION NOT NULL,
    "weatherTemperature" DOUBLE PRECISION NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "failure_dna_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "model_versions" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "version" TEXT NOT NULL,
    "task" TEXT NOT NULL,
    "algorithm" TEXT NOT NULL,
    "accuracy" DOUBLE PRECISION NOT NULL,
    "precisionScore" DOUBLE PRECISION NOT NULL,
    "recallScore" DOUBLE PRECISION NOT NULL,
    "f1Score" DOUBLE PRECISION NOT NULL,
    "trainedAt" TIMESTAMP(3) NOT NULL,
    "datasetVersion" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'active',
    "driftScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "driftStatus" TEXT NOT NULL DEFAULT 'stable',
    "notes" TEXT NOT NULL,
    "notesAr" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "model_versions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "model_audits" (
    "id" TEXT NOT NULL,
    "modelVersionId" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "actor" TEXT NOT NULL,
    "action" TEXT NOT NULL,
    "detail" TEXT NOT NULL,
    "detailAr" TEXT NOT NULL,

    CONSTRAINT "model_audits_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "predictions" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetId" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "horizonMin" INTEGER NOT NULL,
    "eventType" TEXT NOT NULL,
    "probability" DOUBLE PRECISION NOT NULL,
    "confidence" DOUBLE PRECISION NOT NULL,
    "severity" TEXT NOT NULL,
    "riskScore" DOUBLE PRECISION NOT NULL,
    "etaMinutes" INTEGER NOT NULL,
    "etaAt" TIMESTAMP(3) NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'active',
    "source" TEXT NOT NULL DEFAULT 'live',
    "modelVersionId" TEXT NOT NULL,
    "dnaCode" TEXT,
    "dnaSimilarity" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "explanation" TEXT NOT NULL,
    "explanationAr" TEXT NOT NULL,
    "resolvedAt" TIMESTAMP(3),

    CONSTRAINT "predictions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "prediction_factors" (
    "id" TEXT NOT NULL,
    "predictionId" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "contribution" DOUBLE PRECISION NOT NULL,
    "value" DOUBLE PRECISION NOT NULL,
    "unit" TEXT NOT NULL,
    "direction" TEXT NOT NULL DEFAULT 'increase',
    "detail" TEXT NOT NULL,
    "detailAr" TEXT NOT NULL,

    CONSTRAINT "prediction_factors_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "recommendations" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "predictionId" TEXT,
    "assetId" TEXT NOT NULL,
    "actionType" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "magnitudeMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskReduction" DOUBLE PRECISION NOT NULL,
    "costEstimateSar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "durationMin" INTEGER NOT NULL DEFAULT 15,
    "priority" INTEGER NOT NULL DEFAULT 1,
    "status" TEXT NOT NULL DEFAULT 'proposed',
    "requiresRole" TEXT NOT NULL DEFAULT 'operator',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "decidedAt" TIMESTAMP(3),
    "decisionNote" TEXT,

    CONSTRAINT "recommendations_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "scenarios" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "category" TEXT NOT NULL,
    "icon" TEXT NOT NULL,
    "isBuiltIn" BOOLEAN NOT NULL DEFAULT true,
    "targetAssetId" TEXT,
    "targetRegion" TEXT,
    "loadDeltaPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "solarDeltaPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "windDeltaPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "tempDeltaC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "assetOutage" BOOLEAN NOT NULL DEFAULT false,
    "lineOutage" BOOLEAN NOT NULL DEFAULT false,
    "batteryOutage" BOOLEAN NOT NULL DEFAULT false,
    "evSurgeMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "industrialMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "durationMin" INTEGER NOT NULL DEFAULT 120,
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "scenarios_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "simulations" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "scenarioId" TEXT,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'completed',
    "createdById" TEXT,
    "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "completedAt" TIMESTAMP(3),
    "durationMs" INTEGER NOT NULL DEFAULT 0,
    "horizonMin" INTEGER NOT NULL DEFAULT 60,
    "appliedActions" TEXT,
    "notes" TEXT,

    CONSTRAINT "simulations_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "simulation_results" (
    "id" TEXT NOT NULL,
    "simulationId" TEXT NOT NULL,
    "riskBefore" DOUBLE PRECISION NOT NULL,
    "riskAfter" DOUBLE PRECISION NOT NULL,
    "stabilityBefore" DOUBLE PRECISION NOT NULL,
    "stabilityAfter" DOUBLE PRECISION NOT NULL,
    "voltageBefore" DOUBLE PRECISION NOT NULL,
    "voltageAfter" DOUBLE PRECISION NOT NULL,
    "frequencyBefore" DOUBLE PRECISION NOT NULL,
    "frequencyAfter" DOUBLE PRECISION NOT NULL,
    "loadBeforeMw" DOUBLE PRECISION NOT NULL,
    "loadAfterMw" DOUBLE PRECISION NOT NULL,
    "assetStressBefore" DOUBLE PRECISION NOT NULL,
    "assetStressAfter" DOUBLE PRECISION NOT NULL,
    "failureProbBefore" DOUBLE PRECISION NOT NULL,
    "failureProbAfter" DOUBLE PRECISION NOT NULL,
    "regionsAffected" INTEGER NOT NULL,
    "customersImpacted" INTEGER NOT NULL,
    "economicImpactSar" DOUBLE PRECISION NOT NULL,
    "recoveryTimeMin" INTEGER NOT NULL,
    "energyNotServedMwh" DOUBLE PRECISION NOT NULL,
    "co2AvoidedTons" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "verdict" TEXT NOT NULL,
    "verdictAr" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "simulation_results_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "simulation_impacts" (
    "id" TEXT NOT NULL,
    "simulationId" TEXT NOT NULL,
    "assetId" TEXT,
    "regionId" TEXT,
    "metricKey" TEXT NOT NULL,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "baselineValue" DOUBLE PRECISION NOT NULL,
    "scenarioValue" DOUBLE PRECISION NOT NULL,
    "unit" TEXT NOT NULL,
    "severity" TEXT NOT NULL DEFAULT 'info',

    CONSTRAINT "simulation_impacts_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "alerts" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "level" TEXT NOT NULL,
    "assetId" TEXT,
    "regionId" TEXT,
    "predictionId" TEXT,
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "message" TEXT NOT NULL,
    "messageAr" TEXT NOT NULL,
    "riskScore" DOUBLE PRECISION NOT NULL,
    "confidence" DOUBLE PRECISION NOT NULL,
    "expectedAt" TIMESTAMP(3),
    "recommendedAct" TEXT NOT NULL,
    "recommendedActAr" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'new',
    "escalationLevel" INTEGER NOT NULL DEFAULT 1,
    "channels" TEXT NOT NULL DEFAULT 'dashboard',
    "assignedToId" TEXT,
    "acknowledgedById" TEXT,
    "acknowledgedAt" TIMESTAMP(3),
    "resolvedAt" TIMESTAMP(3),
    "resolution" TEXT,
    "resolutionAr" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "alerts_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "escalation_rules" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "minRisk" DOUBLE PRECISION NOT NULL,
    "maxRisk" DOUBLE PRECISION NOT NULL,
    "targetRole" TEXT NOT NULL,
    "channels" TEXT NOT NULL,
    "level" INTEGER NOT NULL,
    "delayMin" INTEGER NOT NULL DEFAULT 0,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "escalation_rules_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "incidents" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "assetId" TEXT,
    "regionId" TEXT,
    "severity" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'closed',
    "startedAt" TIMESTAMP(3) NOT NULL,
    "endedAt" TIMESTAMP(3),
    "durationMin" INTEGER NOT NULL DEFAULT 0,
    "customersAffected" INTEGER NOT NULL DEFAULT 0,
    "energyNotServedMwh" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "economicImpactSar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "rootCause" TEXT NOT NULL,
    "rootCauseAr" TEXT NOT NULL,
    "detectedBy" TEXT NOT NULL DEFAULT 'threshold',
    "nabdhLeadTimeMin" INTEGER NOT NULL DEFAULT 0,
    "thresholdLeadMin" INTEGER NOT NULL DEFAULT 0,
    "wasPrevented" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "incidents_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "incident_events" (
    "id" TEXT NOT NULL,
    "incidentId" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL,
    "offsetMin" INTEGER NOT NULL,
    "phase" TEXT NOT NULL,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "loadPct" DOUBLE PRECISION NOT NULL,
    "tempC" DOUBLE PRECISION NOT NULL,
    "voltageKv" DOUBLE PRECISION NOT NULL,
    "frequencyHz" DOUBLE PRECISION NOT NULL,
    "riskScore" DOUBLE PRECISION NOT NULL,
    "marker" TEXT,
    "note" TEXT NOT NULL,
    "noteAr" TEXT NOT NULL,

    CONSTRAINT "incident_events_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "maintenance_records" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetId" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'completed',
    "priority" TEXT NOT NULL DEFAULT 'medium',
    "scheduledAt" TIMESTAMP(3) NOT NULL,
    "performedAt" TIMESTAMP(3),
    "technicianId" TEXT,
    "findings" TEXT NOT NULL,
    "findingsAr" TEXT NOT NULL,
    "actions" TEXT NOT NULL,
    "actionsAr" TEXT NOT NULL,
    "costSar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "downtimeMin" INTEGER NOT NULL DEFAULT 0,
    "healthBefore" DOUBLE PRECISION NOT NULL,
    "healthAfter" DOUBLE PRECISION NOT NULL,
    "nextDueAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "maintenance_records_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "load_forecasts" (
    "id" TEXT NOT NULL,
    "regionId" TEXT,
    "ts" TIMESTAMP(3) NOT NULL,
    "horizonMin" INTEGER NOT NULL,
    "expectedMw" DOUBLE PRECISION NOT NULL,
    "lowerMw" DOUBLE PRECISION NOT NULL,
    "upperMw" DOUBLE PRECISION NOT NULL,
    "confidence" DOUBLE PRECISION NOT NULL,
    "capacityMw" DOUBLE PRECISION NOT NULL,
    "reserveMarginPct" DOUBLE PRECISION NOT NULL,
    "modelVersionId" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "load_forecasts_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "renewable_forecasts" (
    "id" TEXT NOT NULL,
    "regionId" TEXT,
    "siteId" TEXT,
    "kind" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL,
    "horizonMin" INTEGER NOT NULL,
    "expectedMw" DOUBLE PRECISION NOT NULL,
    "lowerMw" DOUBLE PRECISION NOT NULL,
    "upperMw" DOUBLE PRECISION NOT NULL,
    "confidence" DOUBLE PRECISION NOT NULL,
    "variabilityMw" DOUBLE PRECISION NOT NULL,
    "modelVersionId" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "renewable_forecasts_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "notifications" (
    "id" TEXT NOT NULL,
    "userId" TEXT,
    "roleKey" TEXT,
    "alertId" TEXT,
    "level" TEXT NOT NULL DEFAULT 'info',
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "body" TEXT NOT NULL,
    "bodyAr" TEXT NOT NULL,
    "link" TEXT,
    "channel" TEXT NOT NULL DEFAULT 'dashboard',
    "status" TEXT NOT NULL DEFAULT 'pending',
    "sentAt" TIMESTAMP(3),
    "readAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "notifications_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "integrations" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "category" TEXT NOT NULL,
    "protocol" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'planned',
    "direction" TEXT NOT NULL DEFAULT 'inbound',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "integrations_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "app_settings" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "value" TEXT NOT NULL,
    "valueType" TEXT NOT NULL DEFAULT 'number',
    "groupKey" TEXT NOT NULL,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "minValue" DOUBLE PRECISION,
    "maxValue" DOUBLE PRECISION,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "app_settings_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "demo_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "stage" INTEGER NOT NULL DEFAULT 0,
    "status" TEXT NOT NULL DEFAULT 'running',
    "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "completedAt" TIMESTAMP(3),
    "createdById" TEXT,
    "assetCode" TEXT NOT NULL,
    "notes" TEXT,

    CONSTRAINT "demo_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "grid_nodes" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetId" TEXT,
    "regionCode" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "lat" DOUBLE PRECISION NOT NULL,
    "lon" DOUBLE PRECISION NOT NULL,
    "capacityMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "voltageKv" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "centrality" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "customers" INTEGER NOT NULL DEFAULT 0,
    "isSupply" BOOLEAN NOT NULL DEFAULT false,
    "isLoad" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "grid_nodes_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "grid_edges" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "fromNodeId" TEXT NOT NULL,
    "toNodeId" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "capacityMw" DOUBLE PRECISION NOT NULL,
    "lengthKm" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "impedance" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "shareOfFlow" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "isRedundant" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "grid_edges_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "ai_agents" (
    "id" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "role" TEXT NOT NULL,
    "roleAr" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "descriptionAr" TEXT NOT NULL,
    "ordinal" INTEGER NOT NULL DEFAULT 0,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "ai_agents_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "agent_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "agentId" TEXT NOT NULL,
    "orchestrationId" TEXT,
    "assetId" TEXT,
    "regionCode" TEXT,
    "status" TEXT NOT NULL DEFAULT 'completed',
    "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "finishedAt" TIMESTAMP(3),
    "durationMs" INTEGER NOT NULL DEFAULT 0,
    "summary" TEXT NOT NULL,
    "summaryAr" TEXT NOT NULL,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "dataQuality" DOUBLE PRECISION NOT NULL DEFAULT 100,
    "inputDigest" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "agent_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "agent_findings" (
    "id" TEXT NOT NULL,
    "runId" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "severity" TEXT NOT NULL DEFAULT 'info',
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "detail" TEXT NOT NULL,
    "detailAr" TEXT NOT NULL,
    "metricKey" TEXT NOT NULL DEFAULT '',
    "metricValue" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "metricUnit" TEXT NOT NULL DEFAULT '',
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "ordinal" INTEGER NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "agent_findings_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "cascade_simulations" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "originAssetId" TEXT,
    "originCode" TEXT NOT NULL,
    "triggerKind" TEXT NOT NULL DEFAULT 'failure',
    "horizonMin" INTEGER NOT NULL DEFAULT 60,
    "ts" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "affectedAssets" INTEGER NOT NULL DEFAULT 0,
    "affectedMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "affectedCustomers" INTEGER NOT NULL DEFAULT 0,
    "maxDepth" INTEGER NOT NULL DEFAULT 0,
    "regionalRisk" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "containedAtMin" INTEGER,
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "cascade_simulations_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "cascade_steps" (
    "id" TEXT NOT NULL,
    "simulationId" TEXT NOT NULL,
    "ordinal" INTEGER NOT NULL,
    "depth" INTEGER NOT NULL DEFAULT 1,
    "offsetMin" INTEGER NOT NULL,
    "assetCode" TEXT NOT NULL,
    "assetName" TEXT NOT NULL,
    "assetNameAr" TEXT NOT NULL,
    "effect" TEXT NOT NULL,
    "effectAr" TEXT NOT NULL,
    "mechanism" TEXT NOT NULL DEFAULT 'overload',
    "loadPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "probability" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "severity" TEXT NOT NULL DEFAULT 'medium',
    "customers" INTEGER NOT NULL DEFAULT 0,
    "capacityMw" DOUBLE PRECISION NOT NULL DEFAULT 0,

    CONSTRAINT "cascade_steps_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "counterfactual_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetId" TEXT,
    "assetCode" TEXT NOT NULL,
    "objective" TEXT NOT NULL DEFAULT 'risk_below',
    "targetValue" DOUBLE PRECISION NOT NULL,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "achieved" BOOLEAN NOT NULL DEFAULT false,
    "iterations" INTEGER NOT NULL DEFAULT 0,
    "totalMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "totalCostSar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "horizonMin" INTEGER NOT NULL DEFAULT 45,
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "counterfactual_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "counterfactual_actions" (
    "id" TEXT NOT NULL,
    "runId" TEXT NOT NULL,
    "ordinal" INTEGER NOT NULL DEFAULT 0,
    "actionType" TEXT NOT NULL,
    "actionKey" TEXT NOT NULL,
    "magnitudeMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "durationMin" INTEGER NOT NULL DEFAULT 0,
    "unit" TEXT NOT NULL DEFAULT 'MW',
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "contribution" DOUBLE PRECISION NOT NULL DEFAULT 0,

    CONSTRAINT "counterfactual_actions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "optimization_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "objectiveKey" TEXT NOT NULL DEFAULT 'balanced',
    "candidateCount" INTEGER NOT NULL DEFAULT 0,
    "bestStrategyId" TEXT,
    "bestScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "horizonMin" INTEGER NOT NULL DEFAULT 45,
    "weightsDigest" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "optimization_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "strategies" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "optimizationId" TEXT,
    "assetCode" TEXT NOT NULL,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "kind" TEXT NOT NULL DEFAULT 'generated',
    "rank" INTEGER NOT NULL DEFAULT 0,
    "score" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "costSar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "executionMin" INTEGER NOT NULL DEFAULT 0,
    "customerImpact" INTEGER NOT NULL DEFAULT 0,
    "totalMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "isRecommended" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "strategies_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "strategy_actions" (
    "id" TEXT NOT NULL,
    "strategyId" TEXT NOT NULL,
    "ordinal" INTEGER NOT NULL DEFAULT 0,
    "actionType" TEXT NOT NULL,
    "actionKey" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "magnitudeMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "durationMin" INTEGER NOT NULL DEFAULT 0,
    "costSar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,

    CONSTRAINT "strategy_actions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "strategy_results" (
    "id" TEXT NOT NULL,
    "strategyId" TEXT NOT NULL,
    "metricKey" TEXT NOT NULL,
    "value" DOUBLE PRECISION NOT NULL,
    "normalised" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "weight" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "unit" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "strategy_results_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "prevention_patterns" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "problemKey" TEXT NOT NULL,
    "problem" TEXT NOT NULL,
    "problemAr" TEXT NOT NULL,
    "strategyLabel" TEXT NOT NULL,
    "strategyLabelAr" TEXT NOT NULL,
    "eventType" TEXT NOT NULL,
    "assetTypeKey" TEXT NOT NULL,
    "riskBefore" DOUBLE PRECISION NOT NULL,
    "riskAfter" DOUBLE PRECISION NOT NULL,
    "timesApplied" INTEGER NOT NULL DEFAULT 1,
    "successRate" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "loadPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "tempC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "dnaSimilarity" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "sourceStrategyId" TEXT,
    "isDemo" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "prevention_patterns_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "knowledge_nodes" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "detail" TEXT NOT NULL DEFAULT '',
    "detailAr" TEXT NOT NULL DEFAULT '',
    "regionCode" TEXT,
    "weight" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "refType" TEXT NOT NULL DEFAULT '',
    "refId" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "knowledge_nodes_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "knowledge_edges" (
    "id" TEXT NOT NULL,
    "fromNodeId" TEXT NOT NULL,
    "toNodeId" TEXT NOT NULL,
    "relation" TEXT NOT NULL,
    "relationAr" TEXT NOT NULL,
    "weight" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "knowledge_edges_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "root_cause_analysis" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetId" TEXT,
    "assetCode" TEXT NOT NULL,
    "predictionId" TEXT,
    "incidentId" TEXT,
    "primaryCause" TEXT NOT NULL,
    "primaryCauseAr" TEXT NOT NULL,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "chainJson" TEXT NOT NULL DEFAULT '',
    "alternatives" TEXT NOT NULL DEFAULT '',
    "alternativesAr" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "root_cause_analysis_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "data_quality_scores" (
    "id" TEXT NOT NULL,
    "scopeKind" TEXT NOT NULL DEFAULT 'asset',
    "scopeCode" TEXT NOT NULL,
    "predictionId" TEXT,
    "score" DOUBLE PRECISION NOT NULL,
    "sensorsExpected" INTEGER NOT NULL DEFAULT 0,
    "sensorsReporting" INTEGER NOT NULL DEFAULT 0,
    "staleSensors" INTEGER NOT NULL DEFAULT 0,
    "outlierCount" INTEGER NOT NULL DEFAULT 0,
    "coverageHours" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "band" TEXT NOT NULL DEFAULT 'good',
    "computedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "data_quality_scores_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "sensor_trust_scores" (
    "id" TEXT NOT NULL,
    "sensorId" TEXT NOT NULL,
    "score" DOUBLE PRECISION NOT NULL,
    "missingRate" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "noiseLevel" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "driftPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "outlierRate" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "lastCalibratedAt" TIMESTAMP(3),
    "band" TEXT NOT NULL DEFAULT 'trusted',
    "computedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "sensor_trust_scores_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "decision_records" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "strategyId" TEXT,
    "predictionId" TEXT,
    "orchestrationId" TEXT,
    "modelVersionId" TEXT,
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "rationale" TEXT NOT NULL,
    "rationaleAr" TEXT NOT NULL,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "recommendationConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "dataConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "predictionConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "simulationConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "status" TEXT NOT NULL DEFAULT 'pending',
    "dataTs" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    "outcome" TEXT NOT NULL DEFAULT '',
    "outcomeAr" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "decision_records_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "approvals" (
    "id" TEXT NOT NULL,
    "decisionId" TEXT NOT NULL,
    "step" TEXT NOT NULL DEFAULT 'operator',
    "decision" TEXT NOT NULL DEFAULT 'pending',
    "userId" TEXT,
    "userName" TEXT NOT NULL DEFAULT '',
    "userNameAr" TEXT NOT NULL DEFAULT '',
    "comment" TEXT NOT NULL DEFAULT '',
    "commentAr" TEXT NOT NULL DEFAULT '',
    "decidedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "approvals_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "digital_twins" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "level" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "description" TEXT NOT NULL DEFAULT '',
    "descriptionAr" TEXT NOT NULL DEFAULT '',
    "regionCode" TEXT,
    "siteCode" TEXT,
    "assetId" TEXT,
    "mode" TEXT NOT NULL DEFAULT 'shadow',
    "autonomyLevel" INTEGER NOT NULL DEFAULT 3,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "digital_twins_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_assets" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "assetId" TEXT,
    "assetCode" TEXT NOT NULL,
    "role" TEXT NOT NULL DEFAULT 'member',
    "x" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "y" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "z" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "rotationY" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "shapeKey" TEXT NOT NULL DEFAULT 'box',
    "scale" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_assets_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_relationships" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "fromCode" TEXT NOT NULL,
    "toCode" TEXT NOT NULL,
    "kind" TEXT NOT NULL DEFAULT 'supplies',
    "strength" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "capacityMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_relationships_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_states" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL,
    "source" TEXT NOT NULL DEFAULT 'live',
    "loadPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "loadMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "tempC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "voltageKv" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "healthScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "state" TEXT NOT NULL DEFAULT 'normal',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_states_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_snapshots" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL,
    "reason" TEXT NOT NULL DEFAULT 'pre_simulation',
    "assetCount" INTEGER NOT NULL DEFAULT 0,
    "totalLoadMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "stabilityIndex" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "peakRisk" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "ambientC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "renewableMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "perturbation" TEXT NOT NULL DEFAULT '',
    "stateJson" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_snapshots_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_sensor_bindings" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "sensorId" TEXT,
    "sensorCode" TEXT NOT NULL,
    "channel" TEXT NOT NULL,
    "unit" TEXT NOT NULL DEFAULT '',
    "offsetX" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "offsetY" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "offsetZ" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "isPrimary" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_sensor_bindings_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_simulations" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "snapshotId" TEXT,
    "scenarioId" TEXT,
    "kind" TEXT NOT NULL DEFAULT 'scenario',
    "status" TEXT NOT NULL DEFAULT 'completed',
    "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "finishedAt" TIMESTAMP(3),
    "durationMs" INTEGER NOT NULL DEFAULT 0,
    "horizonMin" INTEGER NOT NULL DEFAULT 180,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "stabilityBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "stabilityAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "assetsAffected" INTEGER NOT NULL DEFAULT 0,
    "downtimeMin" INTEGER NOT NULL DEFAULT 0,
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "resultJson" TEXT NOT NULL DEFAULT '',
    "isShared" BOOLEAN NOT NULL DEFAULT false,
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_simulations_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_scenarios" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "description" TEXT NOT NULL DEFAULT '',
    "descriptionAr" TEXT NOT NULL DEFAULT '',
    "origin" TEXT NOT NULL DEFAULT 'manual',
    "regionCode" TEXT,
    "durationMin" INTEGER NOT NULL DEFAULT 120,
    "isPreset" BOOLEAN NOT NULL DEFAULT false,
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_scenarios_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_events" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "scenarioId" TEXT,
    "ordinal" INTEGER NOT NULL DEFAULT 0,
    "kind" TEXT NOT NULL,
    "label" TEXT NOT NULL,
    "labelAr" TEXT NOT NULL,
    "offsetMin" INTEGER NOT NULL DEFAULT 0,
    "durationMin" INTEGER NOT NULL DEFAULT 60,
    "magnitude" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "unit" TEXT NOT NULL DEFAULT '',
    "targetCode" TEXT,
    "regionCode" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_events_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_deviations" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "channel" TEXT NOT NULL,
    "expectedValue" DOUBLE PRECISION NOT NULL,
    "observedValue" DOUBLE PRECISION NOT NULL,
    "deviationPct" DOUBLE PRECISION NOT NULL,
    "suspectedCause" TEXT NOT NULL DEFAULT 'model_drift',
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "detail" TEXT NOT NULL DEFAULT '',
    "detailAr" TEXT NOT NULL DEFAULT '',
    "status" TEXT NOT NULL DEFAULT 'open',
    "detectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_deviations_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_fidelity_scores" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "score" DOUBLE PRECISION NOT NULL,
    "band" TEXT NOT NULL DEFAULT 'good',
    "sensorCoverage" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "dataFreshness" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "sensorTrust" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "modelCoverage" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "historicalDepth" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "lastSyncAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "sensorsOnline" INTEGER NOT NULL DEFAULT 0,
    "sensorsExpected" INTEGER NOT NULL DEFAULT 0,
    "computedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_fidelity_scores_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_versions" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "version" INTEGER NOT NULL,
    "author" TEXT NOT NULL DEFAULT 'system',
    "authorId" TEXT,
    "change" TEXT NOT NULL,
    "changeAr" TEXT NOT NULL DEFAULT '',
    "reason" TEXT NOT NULL DEFAULT '',
    "reasonAr" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_versions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "safe_operating_envelopes" (
    "id" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "scopeKind" TEXT NOT NULL DEFAULT 'region',
    "scopeCode" TEXT NOT NULL,
    "currentLoadPct" DOUBLE PRECISION NOT NULL,
    "maxRecommendedPct" DOUBLE PRECISION NOT NULL,
    "heatAdjustedMaxPct" DOUBLE PRECISION NOT NULL,
    "reserveMarginPct" DOUBLE PRECISION NOT NULL,
    "ambientC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "breakingPointPct" DOUBLE PRECISION,
    "breakingAssetCode" TEXT,
    "computedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "safe_operating_envelopes_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "resilience_tests" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "disturbance" TEXT NOT NULL,
    "scopeCode" TEXT,
    "magnitude" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "durationMin" INTEGER NOT NULL DEFAULT 120,
    "scoreBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "scoreDuring" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "scoreAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "recoveryMin" INTEGER NOT NULL DEFAULT 0,
    "verdict" TEXT NOT NULL DEFAULT '',
    "verdictAr" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "resilience_tests_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "resilience_results" (
    "id" TEXT NOT NULL,
    "testId" TEXT NOT NULL,
    "phase" TEXT NOT NULL DEFAULT 'before',
    "factorKey" TEXT NOT NULL,
    "value" DOUBLE PRECISION NOT NULL,
    "normalised" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "weight" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "unit" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "resilience_results_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_verifications" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "twinId" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "horizonMin" INTEGER NOT NULL DEFAULT 30,
    "predictionId" TEXT,
    "modelVersion" TEXT NOT NULL DEFAULT '',
    "twinVersion" TEXT NOT NULL DEFAULT '',
    "snapshotCode" TEXT NOT NULL DEFAULT '',
    "dataSnapshotId" TEXT NOT NULL DEFAULT '',
    "predictedAt" TIMESTAMP(3) NOT NULL,
    "horizonAt" TIMESTAMP(3) NOT NULL,
    "observedAt" TIMESTAMP(3),
    "status" TEXT NOT NULL DEFAULT 'pending',
    "predictedRisk" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "observedRisk" DOUBLE PRECISION,
    "predictedConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "meanAbsError" DOUBLE PRECISION,
    "worstChannel" TEXT,
    "worstError" DOUBLE PRECISION,
    "bias" DOUBLE PRECISION,
    "withinInterval" BOOLEAN,
    "fidelityBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "fidelityAfter" DOUBLE PRECISION,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "twin_verifications_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "twin_prediction_errors" (
    "id" TEXT NOT NULL,
    "verificationId" TEXT NOT NULL,
    "channel" TEXT NOT NULL,
    "unit" TEXT NOT NULL DEFAULT '',
    "predicted" DOUBLE PRECISION NOT NULL,
    "observed" DOUBLE PRECISION NOT NULL,
    "absError" DOUBLE PRECISION NOT NULL,
    "pctError" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "intervalLow" DOUBLE PRECISION,
    "intervalHigh" DOUBLE PRECISION,
    "withinInterval" BOOLEAN NOT NULL DEFAULT false,

    CONSTRAINT "twin_prediction_errors_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "verification_metrics" (
    "id" TEXT NOT NULL,
    "scopeKind" TEXT NOT NULL DEFAULT 'national',
    "scopeCode" TEXT NOT NULL DEFAULT '',
    "windowHours" INTEGER NOT NULL DEFAULT 24,
    "sampleCount" INTEGER NOT NULL DEFAULT 0,
    "meanAbsError" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "bias" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "coveragePct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "calibrationGap" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "leadMinutesMean" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "falsePositiveRate" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "missRate" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "precision" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "fidelityMean" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "computedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "verification_metrics_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "physics_constraints" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "scopeKind" TEXT NOT NULL DEFAULT 'asset_type',
    "scopeCode" TEXT NOT NULL DEFAULT '',
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "description" TEXT NOT NULL DEFAULT '',
    "descriptionAr" TEXT NOT NULL DEFAULT '',
    "comparator" TEXT NOT NULL DEFAULT 'lte',
    "limitValue" DOUBLE PRECISION NOT NULL,
    "warnValue" DOUBLE PRECISION,
    "unit" TEXT NOT NULL DEFAULT '%',
    "severity" TEXT NOT NULL DEFAULT 'hard',
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "source" TEXT NOT NULL DEFAULT 'demo_model',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "physics_constraints_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "physics_validation_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "subjectKind" TEXT NOT NULL DEFAULT 'strategy',
    "subjectId" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL DEFAULT '',
    "verdict" TEXT NOT NULL DEFAULT 'valid',
    "checksRun" INTEGER NOT NULL DEFAULT 0,
    "checksFailed" INTEGER NOT NULL DEFAULT 0,
    "warnings" INTEGER NOT NULL DEFAULT 0,
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "runById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "physics_validation_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "physics_checks" (
    "id" TEXT NOT NULL,
    "runId" TEXT NOT NULL,
    "constraintId" TEXT,
    "constraintCode" TEXT NOT NULL DEFAULT '',
    "assetCode" TEXT NOT NULL DEFAULT '',
    "label" TEXT NOT NULL DEFAULT '',
    "labelAr" TEXT NOT NULL DEFAULT '',
    "observedValue" DOUBLE PRECISION NOT NULL,
    "limitValue" DOUBLE PRECISION NOT NULL,
    "unit" TEXT NOT NULL DEFAULT '%',
    "headroom" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "passed" BOOLEAN NOT NULL DEFAULT true,
    "severity" TEXT NOT NULL DEFAULT 'hard',
    "reason" TEXT NOT NULL DEFAULT '',
    "reasonAr" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "physics_checks_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "asset_operating_envelopes" (
    "id" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "currentPct" DOUBLE PRECISION NOT NULL,
    "normalMaxPct" DOUBLE PRECISION NOT NULL,
    "recommendedMaxPct" DOUBLE PRECISION NOT NULL,
    "warningPct" DOUBLE PRECISION NOT NULL,
    "criticalPct" DOUBLE PRECISION NOT NULL,
    "physicalLimitPct" DOUBLE PRECISION NOT NULL DEFAULT 100,
    "adjustedMaxPct" DOUBLE PRECISION NOT NULL,
    "ambientC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "heatPenaltyPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "agePenaltyPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "maintenancePenaltyPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "coolingPenaltyPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "band" TEXT NOT NULL DEFAULT 'normal',
    "headroomPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "source" TEXT NOT NULL DEFAULT 'demo_model',
    "computedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "asset_operating_envelopes_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "uncertainty_estimates" (
    "id" TEXT NOT NULL,
    "subjectKind" TEXT NOT NULL DEFAULT 'prediction',
    "subjectId" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL DEFAULT '',
    "probability" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "expectedMin" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "windowLowMin" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "windowHighMin" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "predictionConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "dataConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "modelConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "physicsConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "twinFidelity" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "rawConfidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "degradedBy" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "degradeReason" TEXT NOT NULL DEFAULT '',
    "degradeReasonAr" TEXT NOT NULL DEFAULT '',
    "computedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "uncertainty_estimates_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "discovery_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "objective" TEXT NOT NULL,
    "mode" TEXT NOT NULL DEFAULT 'balanced',
    "origin" TEXT NOT NULL DEFAULT 'discovery',
    "scopeKind" TEXT NOT NULL DEFAULT 'region',
    "scopeCode" TEXT NOT NULL DEFAULT '',
    "seed" INTEGER NOT NULL DEFAULT 0,
    "maxSimulations" INTEGER NOT NULL DEFAULT 60,
    "simulationsRun" INTEGER NOT NULL DEFAULT 0,
    "maxDurationMs" INTEGER NOT NULL DEFAULT 20000,
    "durationMs" INTEGER NOT NULL DEFAULT 0,
    "status" TEXT NOT NULL DEFAULT 'queued',
    "discovered" INTEGER NOT NULL DEFAULT 0,
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "startedById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "completedAt" TIMESTAMP(3),

    CONSTRAINT "discovery_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "scenario_discoveries" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "runId" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "originAsset" TEXT NOT NULL DEFAULT '',
    "regionCode" TEXT NOT NULL DEFAULT '',
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "cascadeProbability" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "cascadeDepth" INTEGER NOT NULL DEFAULT 0,
    "assetsAffected" INTEGER NOT NULL DEFAULT 0,
    "noveltyScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "probability" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "severity" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "reproducibility" DOUBLE PRECISION NOT NULL DEFAULT 100,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "status" TEXT NOT NULL DEFAULT 'new',
    "narrative" TEXT NOT NULL DEFAULT '',
    "narrativeAr" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "scenario_discoveries_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "discovery_conditions" (
    "id" TEXT NOT NULL,
    "discoveryId" TEXT NOT NULL,
    "leverKey" TEXT NOT NULL,
    "label" TEXT NOT NULL DEFAULT '',
    "labelAr" TEXT NOT NULL DEFAULT '',
    "magnitude" DOUBLE PRECISION NOT NULL,
    "unit" TEXT NOT NULL DEFAULT '%',
    "plausibility" DOUBLE PRECISION NOT NULL DEFAULT 0,

    CONSTRAINT "discovery_conditions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "adversarial_tests" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "twinId" TEXT,
    "assetCode" TEXT NOT NULL,
    "goal" TEXT NOT NULL DEFAULT 'critical',
    "sandboxOnly" BOOLEAN NOT NULL DEFAULT true,
    "found" BOOLEAN NOT NULL DEFAULT false,
    "iterations" INTEGER NOT NULL DEFAULT 0,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "plausibility" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "weakestAsset" TEXT NOT NULL DEFAULT '',
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "adversarial_tests_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "resilience_red_team_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "twinId" TEXT,
    "scopeKind" TEXT NOT NULL DEFAULT 'national',
    "scopeCode" TEXT NOT NULL DEFAULT '',
    "stressKind" TEXT NOT NULL DEFAULT 'combined',
    "title" TEXT NOT NULL DEFAULT '',
    "titleAr" TEXT NOT NULL DEFAULT '',
    "resilienceBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "resilienceDuring" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskDuring" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "assetsStressed" INTEGER NOT NULL DEFAULT 0,
    "weakestFactor" TEXT NOT NULL DEFAULT '',
    "narrative" TEXT NOT NULL DEFAULT '',
    "narrativeAr" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "resilience_red_team_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "resilience_blue_team_runs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "redRunId" TEXT NOT NULL,
    "strategyLabel" TEXT NOT NULL DEFAULT '',
    "strategyLabelAr" TEXT NOT NULL DEFAULT '',
    "resilienceAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "recoveryMin" INTEGER NOT NULL DEFAULT 0,
    "costIndex" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "customersImpacted" INTEGER NOT NULL DEFAULT 0,
    "isRecommended" BOOLEAN NOT NULL DEFAULT false,
    "rank" INTEGER NOT NULL DEFAULT 0,
    "narrative" TEXT NOT NULL DEFAULT '',
    "narrativeAr" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "resilience_blue_team_runs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "blue_team_actions" (
    "id" TEXT NOT NULL,
    "blueRunId" TEXT NOT NULL,
    "actionKey" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL DEFAULT '',
    "label" TEXT NOT NULL DEFAULT '',
    "labelAr" TEXT NOT NULL DEFAULT '',
    "magnitudeMw" DOUBLE PRECISION NOT NULL DEFAULT 0,

    CONSTRAINT "blue_team_actions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "decision_memory" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "decisionId" TEXT,
    "assetCode" TEXT NOT NULL,
    "regionCode" TEXT NOT NULL DEFAULT '',
    "assetTypeKey" TEXT NOT NULL DEFAULT '',
    "title" TEXT NOT NULL DEFAULT '',
    "titleAr" TEXT NOT NULL DEFAULT '',
    "loadPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "tempC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "ambientC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "healthScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "hourOfDay" INTEGER NOT NULL DEFAULT 0,
    "monthOfYear" INTEGER NOT NULL DEFAULT 0,
    "dnaPatternCode" TEXT NOT NULL DEFAULT '',
    "dnaSimilarity" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "rootCauseKey" TEXT NOT NULL DEFAULT '',
    "cascadeDepth" INTEGER NOT NULL DEFAULT 0,
    "strategyKey" TEXT NOT NULL DEFAULT '',
    "strategyLabel" TEXT NOT NULL DEFAULT '',
    "strategyLabelAr" TEXT NOT NULL DEFAULT '',
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "approverId" TEXT,
    "approvedAt" TIMESTAMP(3),
    "evidenceKind" TEXT NOT NULL DEFAULT 'simulated',
    "outcomeStatus" TEXT NOT NULL DEFAULT 'pending',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "decision_memory_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "decision_outcomes" (
    "id" TEXT NOT NULL,
    "memoryId" TEXT NOT NULL,
    "result" TEXT NOT NULL DEFAULT 'not_observed',
    "observedRisk" DOUBLE PRECISION,
    "predictedRisk" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "deltaRisk" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "observedAt" TIMESTAMP(3),
    "evidenceKind" TEXT NOT NULL DEFAULT 'simulated',
    "notes" TEXT NOT NULL DEFAULT '',
    "notesAr" TEXT NOT NULL DEFAULT '',
    "recordedById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "decision_outcomes_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "decision_lessons" (
    "id" TEXT NOT NULL,
    "memoryId" TEXT NOT NULL,
    "text" TEXT NOT NULL,
    "textAr" TEXT NOT NULL DEFAULT '',
    "authorId" TEXT,
    "isApproved" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "decision_lessons_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "learning_candidates" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "kind" TEXT NOT NULL DEFAULT 'pattern',
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "reason" TEXT NOT NULL DEFAULT '',
    "reasonAr" TEXT NOT NULL DEFAULT '',
    "evidence" TEXT NOT NULL DEFAULT '',
    "evidenceAr" TEXT NOT NULL DEFAULT '',
    "eventCount" INTEGER NOT NULL DEFAULT 0,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "supportPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "proposedChange" TEXT NOT NULL DEFAULT '',
    "proposedChangeAr" TEXT NOT NULL DEFAULT '',
    "status" TEXT NOT NULL DEFAULT 'new',
    "reviewedById" TEXT,
    "reviewedAt" TIMESTAMP(3),
    "reviewNote" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "learning_candidates_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "strategy_tradeoffs" (
    "id" TEXT NOT NULL,
    "runId" TEXT NOT NULL,
    "strategyId" TEXT NOT NULL,
    "metricKey" TEXT NOT NULL,
    "value" DOUBLE PRECISION NOT NULL,
    "normalised" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "unit" TEXT NOT NULL DEFAULT '',
    "direction" TEXT NOT NULL DEFAULT 'lower_is_better',

    CONSTRAINT "strategy_tradeoffs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "pareto_strategies" (
    "id" TEXT NOT NULL,
    "runId" TEXT NOT NULL,
    "strategyId" TEXT NOT NULL,
    "strategyLabel" TEXT NOT NULL DEFAULT '',
    "strategyLabelAr" TEXT NOT NULL DEFAULT '',
    "isOnFrontier" BOOLEAN NOT NULL DEFAULT false,
    "corner" TEXT NOT NULL DEFAULT '',
    "dominatedBy" INTEGER NOT NULL DEFAULT 0,
    "crowdingDistance" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "rank" INTEGER NOT NULL DEFAULT 0,
    "rejectionReason" TEXT NOT NULL DEFAULT '',
    "rejectionReasonAr" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "pareto_strategies_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "cascade_probabilities" (
    "id" TEXT NOT NULL,
    "simulationId" TEXT NOT NULL,
    "parentCode" TEXT NOT NULL DEFAULT '',
    "assetCode" TEXT NOT NULL,
    "depth" INTEGER NOT NULL DEFAULT 0,
    "probability" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "delayMin" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "unservedMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "customersAtRisk" INTEGER NOT NULL DEFAULT 0,
    "mechanism" TEXT NOT NULL DEFAULT '',
    "outcome" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "cascade_probabilities_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "cascade_breakpoints" (
    "id" TEXT NOT NULL,
    "simulationId" TEXT NOT NULL,
    "huntCode" TEXT NOT NULL DEFAULT '',
    "assetCode" TEXT NOT NULL,
    "depth" INTEGER NOT NULL DEFAULT 0,
    "riskReduction" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "branchesStopped" INTEGER NOT NULL DEFAULT 0,
    "customersProtected" INTEGER NOT NULL DEFAULT 0,
    "interventionMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "costIndex" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "feasible" BOOLEAN NOT NULL DEFAULT true,
    "isBest" BOOLEAN NOT NULL DEFAULT false,
    "rationale" TEXT NOT NULL DEFAULT '',
    "rationaleAr" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "cascade_breakpoints_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "evidence_nodes" (
    "id" TEXT NOT NULL,
    "bundleCode" TEXT NOT NULL,
    "nodeKey" TEXT NOT NULL,
    "stage" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "detail" TEXT NOT NULL DEFAULT '',
    "detailAr" TEXT NOT NULL DEFAULT '',
    "sourceType" TEXT NOT NULL DEFAULT 'synthetic',
    "sourceId" TEXT NOT NULL DEFAULT '',
    "value" DOUBLE PRECISION,
    "unit" TEXT NOT NULL DEFAULT '',
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "freshnessMin" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "modelVersion" TEXT NOT NULL DEFAULT '',
    "orderIndex" INTEGER NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "evidence_nodes_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "evidence_edges" (
    "id" TEXT NOT NULL,
    "bundleCode" TEXT NOT NULL,
    "fromKey" TEXT NOT NULL,
    "toKey" TEXT NOT NULL,
    "relation" TEXT NOT NULL DEFAULT 'derives',
    "weight" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "label" TEXT NOT NULL DEFAULT '',
    "labelAr" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "evidence_edges_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "model_drift_events" (
    "id" TEXT NOT NULL,
    "modelVersionId" TEXT,
    "modelKey" TEXT NOT NULL DEFAULT '',
    "driftKind" TEXT NOT NULL DEFAULT 'performance',
    "metricKey" TEXT NOT NULL DEFAULT '',
    "baseline" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "observed" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "deltaPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "threshold" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "severity" TEXT NOT NULL DEFAULT 'watch',
    "sampleCount" INTEGER NOT NULL DEFAULT 0,
    "detail" TEXT NOT NULL DEFAULT '',
    "detailAr" TEXT NOT NULL DEFAULT '',
    "status" TEXT NOT NULL DEFAULT 'open',
    "detectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "model_drift_events_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "data_provenance" (
    "id" TEXT NOT NULL,
    "subjectKind" TEXT NOT NULL,
    "subjectId" TEXT NOT NULL,
    "fieldKey" TEXT NOT NULL,
    "sourceType" TEXT NOT NULL DEFAULT 'synthetic',
    "sourceId" TEXT NOT NULL DEFAULT '',
    "producedAt" TIMESTAMP(3) NOT NULL,
    "freshnessMin" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "transformation" TEXT NOT NULL DEFAULT '',
    "modelVersion" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "data_provenance_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "approval_records" (
    "id" TEXT NOT NULL,
    "subjectKind" TEXT NOT NULL,
    "subjectId" TEXT NOT NULL,
    "requiredRole" TEXT NOT NULL DEFAULT 'supervisor',
    "status" TEXT NOT NULL DEFAULT 'requested',
    "requestedById" TEXT,
    "decidedById" TEXT,
    "decidedAt" TIMESTAMP(3),
    "twoPersonRequired" BOOLEAN NOT NULL DEFAULT false,
    "secondApproverId" TEXT,
    "secondApprovedAt" TIMESTAMP(3),
    "note" TEXT NOT NULL DEFAULT '',
    "noteAr" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "approval_records_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "compute_jobs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'queued',
    "progress" INTEGER NOT NULL DEFAULT 0,
    "stepLabel" TEXT NOT NULL DEFAULT '',
    "stepLabelAr" TEXT NOT NULL DEFAULT '',
    "budgetIterations" INTEGER NOT NULL DEFAULT 0,
    "usedIterations" INTEGER NOT NULL DEFAULT 0,
    "budgetMs" INTEGER NOT NULL DEFAULT 0,
    "durationMs" INTEGER NOT NULL DEFAULT 0,
    "resultKind" TEXT NOT NULL DEFAULT '',
    "resultId" TEXT NOT NULL DEFAULT '',
    "error" TEXT NOT NULL DEFAULT '',
    "ownerId" TEXT,
    "startedAt" TIMESTAMP(3),
    "finishedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "compute_jobs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "integration_connectors" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "nameAr" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "protocol" TEXT NOT NULL DEFAULT 'rest',
    "mode" TEXT NOT NULL DEFAULT 'demo',
    "status" TEXT NOT NULL DEFAULT 'disabled',
    "direction" TEXT NOT NULL DEFAULT 'inbound',
    "description" TEXT NOT NULL DEFAULT '',
    "descriptionAr" TEXT NOT NULL DEFAULT '',
    "endpoint" TEXT NOT NULL DEFAULT '',
    "authKind" TEXT NOT NULL DEFAULT 'none',
    "secretRef" TEXT NOT NULL DEFAULT '',
    "pollSeconds" INTEGER NOT NULL DEFAULT 15,
    "timeoutMs" INTEGER NOT NULL DEFAULT 5000,
    "retryLimit" INTEGER NOT NULL DEFAULT 3,
    "rateLimitPerMin" INTEGER NOT NULL DEFAULT 600,
    "lastConnectedAt" TIMESTAMP(3),
    "lastSyncAt" TIMESTAMP(3),
    "latencyMs" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "recordsReceived" INTEGER NOT NULL DEFAULT 0,
    "errorCount" INTEGER NOT NULL DEFAULT 0,
    "healthScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "dataQuality" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "eventsPerMin" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "faultKind" TEXT NOT NULL DEFAULT '',
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "integration_connectors_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "integration_mappings" (
    "id" TEXT NOT NULL,
    "connectorId" TEXT NOT NULL,
    "sourceField" TEXT NOT NULL,
    "targetField" TEXT NOT NULL,
    "dataType" TEXT NOT NULL DEFAULT 'number',
    "sourceUnit" TEXT NOT NULL DEFAULT '',
    "targetUnit" TEXT NOT NULL DEFAULT '',
    "transform" TEXT NOT NULL DEFAULT 'none',
    "defaultValue" TEXT NOT NULL DEFAULT '',
    "minValue" DOUBLE PRECISION,
    "maxValue" DOUBLE PRECISION,
    "isRequired" BOOLEAN NOT NULL DEFAULT false,
    "notes" TEXT NOT NULL DEFAULT '',

    CONSTRAINT "integration_mappings_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "integration_events" (
    "id" TEXT NOT NULL,
    "connectorId" TEXT NOT NULL,
    "kind" TEXT NOT NULL,
    "recordsIn" INTEGER NOT NULL DEFAULT 0,
    "recordsAccepted" INTEGER NOT NULL DEFAULT 0,
    "recordsRejected" INTEGER NOT NULL DEFAULT 0,
    "latencyMs" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "detail" TEXT NOT NULL DEFAULT '',
    "detailAr" TEXT NOT NULL DEFAULT '',
    "severity" TEXT NOT NULL DEFAULT 'info',
    "ts" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "integration_events_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "integration_health_samples" (
    "id" TEXT NOT NULL,
    "connectorId" TEXT NOT NULL,
    "healthScore" DOUBLE PRECISION NOT NULL,
    "dataQuality" DOUBLE PRECISION NOT NULL,
    "latencyMs" DOUBLE PRECISION NOT NULL,
    "completeness" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "freshness" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "validity" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "consistency" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "availability" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "trust" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "ts" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "integration_health_samples_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "risk_preventions" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "discoveryId" TEXT NOT NULL,
    "assetCode" TEXT NOT NULL,
    "achieved" BOOLEAN NOT NULL DEFAULT false,
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "targetRisk" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "totalMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "totalCostSar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "evidenceKind" TEXT NOT NULL DEFAULT 'simulated',
    "summary" TEXT NOT NULL DEFAULT '',
    "summaryAr" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "risk_preventions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "risk_prevention_doses" (
    "id" TEXT NOT NULL,
    "preventionId" TEXT NOT NULL,
    "leverKey" TEXT NOT NULL,
    "label" TEXT NOT NULL DEFAULT '',
    "labelAr" TEXT NOT NULL DEFAULT '',
    "amount" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "unit" TEXT NOT NULL DEFAULT 'MW',
    "utilisation" DOUBLE PRECISION NOT NULL DEFAULT 0,

    CONSTRAINT "risk_prevention_doses_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "decision_proofs" (
    "id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "decisionId" TEXT,
    "assetCode" TEXT NOT NULL DEFAULT '',
    "bundleCode" TEXT NOT NULL DEFAULT '',
    "predictionId" TEXT NOT NULL DEFAULT '',
    "simulationId" TEXT NOT NULL DEFAULT '',
    "twinSnapshotCode" TEXT NOT NULL DEFAULT '',
    "dataSnapshotId" TEXT NOT NULL DEFAULT '',
    "modelVersion" TEXT NOT NULL DEFAULT '',
    "twinVersion" TEXT NOT NULL DEFAULT '',
    "riskBefore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "riskAfter" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "recommendation" TEXT NOT NULL DEFAULT '',
    "recommendationAr" TEXT NOT NULL DEFAULT '',
    "physicsVerdict" TEXT NOT NULL DEFAULT '',
    "weakestLinkKey" TEXT NOT NULL DEFAULT '',
    "weakestLinkScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "measuredSharePct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "outcome" TEXT NOT NULL DEFAULT 'pending',
    "evidenceKind" TEXT NOT NULL DEFAULT 'simulated',
    "flowMethod" TEXT NOT NULL DEFAULT 'none',
    "flowConverged" BOOLEAN NOT NULL DEFAULT false,
    "flowIterations" INTEGER NOT NULL DEFAULT 0,
    "flowConvergence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "impedanceSource" TEXT NOT NULL DEFAULT 'typical',
    "forecastVersion" TEXT NOT NULL DEFAULT '',
    "topologyVersion" TEXT NOT NULL DEFAULT '',
    "evidenceHash" TEXT NOT NULL DEFAULT '',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "decision_proofs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "replay_events" (
    "id" TEXT NOT NULL,
    "proofId" TEXT NOT NULL,
    "seq" INTEGER NOT NULL,
    "ts" TIMESTAMP(3) NOT NULL,
    "stage" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "titleAr" TEXT NOT NULL,
    "detail" TEXT NOT NULL DEFAULT '',
    "detailAr" TEXT NOT NULL DEFAULT '',
    "riskScore" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "loadPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "tempC" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "state" TEXT NOT NULL DEFAULT 'normal',
    "sourceType" TEXT NOT NULL DEFAULT 'simulated',
    "confidence" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "voltagePu" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "angleDeg" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "activeMw" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "reactiveMvar" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "currentA" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "loadingPct" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "hasPhysics" BOOLEAN NOT NULL DEFAULT false,

    CONSTRAINT "replay_events_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");

-- CreateIndex
CREATE UNIQUE INDEX "users_employeeId_key" ON "users"("employeeId");

-- CreateIndex
CREATE INDEX "users_isActive_idx" ON "users"("isActive");

-- CreateIndex
CREATE UNIQUE INDEX "roles_key_key" ON "roles"("key");

-- CreateIndex
CREATE UNIQUE INDEX "permissions_key_key" ON "permissions"("key");

-- CreateIndex
CREATE INDEX "permissions_resource_idx" ON "permissions"("resource");

-- CreateIndex
CREATE INDEX "role_permissions_roleId_idx" ON "role_permissions"("roleId");

-- CreateIndex
CREATE UNIQUE INDEX "role_permissions_roleId_permissionId_key" ON "role_permissions"("roleId", "permissionId");

-- CreateIndex
CREATE INDEX "user_roles_userId_idx" ON "user_roles"("userId");

-- CreateIndex
CREATE UNIQUE INDEX "user_roles_userId_roleId_key" ON "user_roles"("userId", "roleId");

-- CreateIndex
CREATE UNIQUE INDEX "sessions_tokenId_key" ON "sessions"("tokenId");

-- CreateIndex
CREATE INDEX "sessions_userId_idx" ON "sessions"("userId");

-- CreateIndex
CREATE INDEX "audit_logs_ts_idx" ON "audit_logs"("ts");

-- CreateIndex
CREATE INDEX "audit_logs_userId_idx" ON "audit_logs"("userId");

-- CreateIndex
CREATE INDEX "audit_logs_action_idx" ON "audit_logs"("action");

-- CreateIndex
CREATE INDEX "audit_logs_entity_entityId_idx" ON "audit_logs"("entity", "entityId");

-- CreateIndex
CREATE UNIQUE INDEX "regions_code_key" ON "regions"("code");

-- CreateIndex
CREATE UNIQUE INDEX "sites_code_key" ON "sites"("code");

-- CreateIndex
CREATE INDEX "sites_regionId_idx" ON "sites"("regionId");

-- CreateIndex
CREATE UNIQUE INDEX "asset_types_key_key" ON "asset_types"("key");

-- CreateIndex
CREATE UNIQUE INDEX "assets_code_key" ON "assets"("code");

-- CreateIndex
CREATE UNIQUE INDEX "assets_serialNumber_key" ON "assets"("serialNumber");

-- CreateIndex
CREATE INDEX "assets_regionId_idx" ON "assets"("regionId");

-- CreateIndex
CREATE INDEX "assets_siteId_idx" ON "assets"("siteId");

-- CreateIndex
CREATE INDEX "assets_assetTypeId_idx" ON "assets"("assetTypeId");

-- CreateIndex
CREATE INDEX "assets_status_idx" ON "assets"("status");

-- CreateIndex
CREATE INDEX "assets_criticality_idx" ON "assets"("criticality");

-- CreateIndex
CREATE UNIQUE INDEX "sensors_code_key" ON "sensors"("code");

-- CreateIndex
CREATE INDEX "sensors_assetId_idx" ON "sensors"("assetId");

-- CreateIndex
CREATE INDEX "sensors_kind_idx" ON "sensors"("kind");

-- CreateIndex
CREATE INDEX "sensor_readings_assetId_kind_ts_idx" ON "sensor_readings"("assetId", "kind", "ts");

-- CreateIndex
CREATE INDEX "sensor_readings_ts_idx" ON "sensor_readings"("ts");

-- CreateIndex
CREATE INDEX "weather_data_regionId_ts_idx" ON "weather_data"("regionId", "ts");

-- CreateIndex
CREATE UNIQUE INDEX "failure_patterns_code_key" ON "failure_patterns"("code");

-- CreateIndex
CREATE INDEX "failure_patterns_eventType_idx" ON "failure_patterns"("eventType");

-- CreateIndex
CREATE INDEX "failure_patterns_assetTypeKey_idx" ON "failure_patterns"("assetTypeKey");

-- CreateIndex
CREATE UNIQUE INDEX "failure_dna_patternId_key" ON "failure_dna"("patternId");

-- CreateIndex
CREATE UNIQUE INDEX "failure_dna_code_key" ON "failure_dna"("code");

-- CreateIndex
CREATE INDEX "model_versions_status_idx" ON "model_versions"("status");

-- CreateIndex
CREATE UNIQUE INDEX "model_versions_key_version_key" ON "model_versions"("key", "version");

-- CreateIndex
CREATE INDEX "model_audits_modelVersionId_ts_idx" ON "model_audits"("modelVersionId", "ts");

-- CreateIndex
CREATE UNIQUE INDEX "predictions_code_key" ON "predictions"("code");

-- CreateIndex
CREATE INDEX "predictions_assetId_createdAt_idx" ON "predictions"("assetId", "createdAt");

-- CreateIndex
CREATE INDEX "predictions_status_idx" ON "predictions"("status");

-- CreateIndex
CREATE INDEX "predictions_riskScore_idx" ON "predictions"("riskScore");

-- CreateIndex
CREATE INDEX "prediction_factors_predictionId_idx" ON "prediction_factors"("predictionId");

-- CreateIndex
CREATE UNIQUE INDEX "recommendations_code_key" ON "recommendations"("code");

-- CreateIndex
CREATE INDEX "recommendations_predictionId_idx" ON "recommendations"("predictionId");

-- CreateIndex
CREATE INDEX "recommendations_assetId_idx" ON "recommendations"("assetId");

-- CreateIndex
CREATE INDEX "recommendations_status_idx" ON "recommendations"("status");

-- CreateIndex
CREATE UNIQUE INDEX "scenarios_key_key" ON "scenarios"("key");

-- CreateIndex
CREATE INDEX "scenarios_category_idx" ON "scenarios"("category");

-- CreateIndex
CREATE UNIQUE INDEX "simulations_code_key" ON "simulations"("code");

-- CreateIndex
CREATE INDEX "simulations_createdById_idx" ON "simulations"("createdById");

-- CreateIndex
CREATE INDEX "simulations_startedAt_idx" ON "simulations"("startedAt");

-- CreateIndex
CREATE UNIQUE INDEX "simulation_results_simulationId_key" ON "simulation_results"("simulationId");

-- CreateIndex
CREATE INDEX "simulation_impacts_simulationId_idx" ON "simulation_impacts"("simulationId");

-- CreateIndex
CREATE UNIQUE INDEX "alerts_code_key" ON "alerts"("code");

-- CreateIndex
CREATE INDEX "alerts_status_idx" ON "alerts"("status");

-- CreateIndex
CREATE INDEX "alerts_level_idx" ON "alerts"("level");

-- CreateIndex
CREATE INDEX "alerts_createdAt_idx" ON "alerts"("createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "incidents_code_key" ON "incidents"("code");

-- CreateIndex
CREATE INDEX "incidents_severity_idx" ON "incidents"("severity");

-- CreateIndex
CREATE INDEX "incidents_startedAt_idx" ON "incidents"("startedAt");

-- CreateIndex
CREATE INDEX "incident_events_incidentId_offsetMin_idx" ON "incident_events"("incidentId", "offsetMin");

-- CreateIndex
CREATE UNIQUE INDEX "maintenance_records_code_key" ON "maintenance_records"("code");

-- CreateIndex
CREATE INDEX "maintenance_records_assetId_performedAt_idx" ON "maintenance_records"("assetId", "performedAt");

-- CreateIndex
CREATE INDEX "maintenance_records_status_idx" ON "maintenance_records"("status");

-- CreateIndex
CREATE INDEX "load_forecasts_regionId_ts_idx" ON "load_forecasts"("regionId", "ts");

-- CreateIndex
CREATE INDEX "load_forecasts_horizonMin_idx" ON "load_forecasts"("horizonMin");

-- CreateIndex
CREATE INDEX "renewable_forecasts_regionId_kind_ts_idx" ON "renewable_forecasts"("regionId", "kind", "ts");

-- CreateIndex
CREATE INDEX "notifications_userId_status_idx" ON "notifications"("userId", "status");

-- CreateIndex
CREATE UNIQUE INDEX "integrations_key_key" ON "integrations"("key");

-- CreateIndex
CREATE UNIQUE INDEX "app_settings_key_key" ON "app_settings"("key");

-- CreateIndex
CREATE INDEX "app_settings_groupKey_idx" ON "app_settings"("groupKey");

-- CreateIndex
CREATE UNIQUE INDEX "demo_runs_code_key" ON "demo_runs"("code");

-- CreateIndex
CREATE UNIQUE INDEX "grid_nodes_code_key" ON "grid_nodes"("code");

-- CreateIndex
CREATE INDEX "grid_nodes_regionCode_idx" ON "grid_nodes"("regionCode");

-- CreateIndex
CREATE INDEX "grid_nodes_kind_idx" ON "grid_nodes"("kind");

-- CreateIndex
CREATE UNIQUE INDEX "grid_edges_code_key" ON "grid_edges"("code");

-- CreateIndex
CREATE INDEX "grid_edges_fromNodeId_idx" ON "grid_edges"("fromNodeId");

-- CreateIndex
CREATE INDEX "grid_edges_toNodeId_idx" ON "grid_edges"("toNodeId");

-- CreateIndex
CREATE UNIQUE INDEX "ai_agents_key_key" ON "ai_agents"("key");

-- CreateIndex
CREATE UNIQUE INDEX "agent_runs_code_key" ON "agent_runs"("code");

-- CreateIndex
CREATE INDEX "agent_runs_agentId_startedAt_idx" ON "agent_runs"("agentId", "startedAt");

-- CreateIndex
CREATE INDEX "agent_runs_orchestrationId_idx" ON "agent_runs"("orchestrationId");

-- CreateIndex
CREATE INDEX "agent_findings_runId_idx" ON "agent_findings"("runId");

-- CreateIndex
CREATE UNIQUE INDEX "cascade_simulations_code_key" ON "cascade_simulations"("code");

-- CreateIndex
CREATE INDEX "cascade_simulations_originCode_idx" ON "cascade_simulations"("originCode");

-- CreateIndex
CREATE INDEX "cascade_simulations_createdAt_idx" ON "cascade_simulations"("createdAt");

-- CreateIndex
CREATE INDEX "cascade_steps_simulationId_ordinal_idx" ON "cascade_steps"("simulationId", "ordinal");

-- CreateIndex
CREATE UNIQUE INDEX "counterfactual_runs_code_key" ON "counterfactual_runs"("code");

-- CreateIndex
CREATE INDEX "counterfactual_runs_assetCode_idx" ON "counterfactual_runs"("assetCode");

-- CreateIndex
CREATE INDEX "counterfactual_actions_runId_idx" ON "counterfactual_actions"("runId");

-- CreateIndex
CREATE UNIQUE INDEX "optimization_runs_code_key" ON "optimization_runs"("code");

-- CreateIndex
CREATE INDEX "optimization_runs_assetCode_idx" ON "optimization_runs"("assetCode");

-- CreateIndex
CREATE UNIQUE INDEX "strategies_code_key" ON "strategies"("code");

-- CreateIndex
CREATE INDEX "strategies_assetCode_idx" ON "strategies"("assetCode");

-- CreateIndex
CREATE INDEX "strategy_actions_strategyId_idx" ON "strategy_actions"("strategyId");

-- CreateIndex
CREATE INDEX "strategy_results_strategyId_idx" ON "strategy_results"("strategyId");

-- CreateIndex
CREATE UNIQUE INDEX "prevention_patterns_code_key" ON "prevention_patterns"("code");

-- CreateIndex
CREATE INDEX "prevention_patterns_problemKey_idx" ON "prevention_patterns"("problemKey");

-- CreateIndex
CREATE INDEX "prevention_patterns_eventType_idx" ON "prevention_patterns"("eventType");

-- CreateIndex
CREATE UNIQUE INDEX "knowledge_nodes_code_key" ON "knowledge_nodes"("code");

-- CreateIndex
CREATE INDEX "knowledge_nodes_kind_idx" ON "knowledge_nodes"("kind");

-- CreateIndex
CREATE INDEX "knowledge_nodes_regionCode_idx" ON "knowledge_nodes"("regionCode");

-- CreateIndex
CREATE INDEX "knowledge_edges_fromNodeId_idx" ON "knowledge_edges"("fromNodeId");

-- CreateIndex
CREATE INDEX "knowledge_edges_toNodeId_idx" ON "knowledge_edges"("toNodeId");

-- CreateIndex
CREATE UNIQUE INDEX "root_cause_analysis_code_key" ON "root_cause_analysis"("code");

-- CreateIndex
CREATE INDEX "root_cause_analysis_assetCode_idx" ON "root_cause_analysis"("assetCode");

-- CreateIndex
CREATE INDEX "data_quality_scores_score_idx" ON "data_quality_scores"("score");

-- CreateIndex
CREATE UNIQUE INDEX "data_quality_scores_scopeKind_scopeCode_key" ON "data_quality_scores"("scopeKind", "scopeCode");

-- CreateIndex
CREATE UNIQUE INDEX "sensor_trust_scores_sensorId_key" ON "sensor_trust_scores"("sensorId");

-- CreateIndex
CREATE INDEX "sensor_trust_scores_score_idx" ON "sensor_trust_scores"("score");

-- CreateIndex
CREATE UNIQUE INDEX "decision_records_code_key" ON "decision_records"("code");

-- CreateIndex
CREATE INDEX "decision_records_assetCode_idx" ON "decision_records"("assetCode");

-- CreateIndex
CREATE INDEX "decision_records_status_idx" ON "decision_records"("status");

-- CreateIndex
CREATE INDEX "approvals_decisionId_idx" ON "approvals"("decisionId");

-- CreateIndex
CREATE UNIQUE INDEX "digital_twins_code_key" ON "digital_twins"("code");

-- CreateIndex
CREATE INDEX "digital_twins_level_idx" ON "digital_twins"("level");

-- CreateIndex
CREATE INDEX "digital_twins_regionCode_idx" ON "digital_twins"("regionCode");

-- CreateIndex
CREATE INDEX "twin_assets_assetCode_idx" ON "twin_assets"("assetCode");

-- CreateIndex
CREATE UNIQUE INDEX "twin_assets_twinId_assetCode_key" ON "twin_assets"("twinId", "assetCode");

-- CreateIndex
CREATE INDEX "twin_relationships_twinId_idx" ON "twin_relationships"("twinId");

-- CreateIndex
CREATE INDEX "twin_relationships_fromCode_idx" ON "twin_relationships"("fromCode");

-- CreateIndex
CREATE INDEX "twin_states_twinId_ts_idx" ON "twin_states"("twinId", "ts");

-- CreateIndex
CREATE INDEX "twin_states_assetCode_idx" ON "twin_states"("assetCode");

-- CreateIndex
CREATE UNIQUE INDEX "twin_snapshots_code_key" ON "twin_snapshots"("code");

-- CreateIndex
CREATE INDEX "twin_snapshots_twinId_ts_idx" ON "twin_snapshots"("twinId", "ts");

-- CreateIndex
CREATE INDEX "twin_sensor_bindings_assetCode_idx" ON "twin_sensor_bindings"("assetCode");

-- CreateIndex
CREATE UNIQUE INDEX "twin_sensor_bindings_twinId_sensorCode_key" ON "twin_sensor_bindings"("twinId", "sensorCode");

-- CreateIndex
CREATE UNIQUE INDEX "twin_simulations_code_key" ON "twin_simulations"("code");

-- CreateIndex
CREATE INDEX "twin_simulations_twinId_createdAt_idx" ON "twin_simulations"("twinId", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "twin_scenarios_code_key" ON "twin_scenarios"("code");

-- CreateIndex
CREATE INDEX "twin_scenarios_twinId_idx" ON "twin_scenarios"("twinId");

-- CreateIndex
CREATE INDEX "twin_events_twinId_idx" ON "twin_events"("twinId");

-- CreateIndex
CREATE INDEX "twin_events_scenarioId_ordinal_idx" ON "twin_events"("scenarioId", "ordinal");

-- CreateIndex
CREATE INDEX "twin_deviations_twinId_detectedAt_idx" ON "twin_deviations"("twinId", "detectedAt");

-- CreateIndex
CREATE INDEX "twin_deviations_assetCode_idx" ON "twin_deviations"("assetCode");

-- CreateIndex
CREATE INDEX "twin_fidelity_scores_twinId_computedAt_idx" ON "twin_fidelity_scores"("twinId", "computedAt");

-- CreateIndex
CREATE UNIQUE INDEX "twin_versions_twinId_version_key" ON "twin_versions"("twinId", "version");

-- CreateIndex
CREATE INDEX "safe_operating_envelopes_twinId_computedAt_idx" ON "safe_operating_envelopes"("twinId", "computedAt");

-- CreateIndex
CREATE UNIQUE INDEX "resilience_tests_code_key" ON "resilience_tests"("code");

-- CreateIndex
CREATE INDEX "resilience_tests_twinId_createdAt_idx" ON "resilience_tests"("twinId", "createdAt");

-- CreateIndex
CREATE INDEX "resilience_results_testId_phase_idx" ON "resilience_results"("testId", "phase");

-- CreateIndex
CREATE UNIQUE INDEX "twin_verifications_code_key" ON "twin_verifications"("code");

-- CreateIndex
CREATE INDEX "twin_verifications_twinId_predictedAt_idx" ON "twin_verifications"("twinId", "predictedAt");

-- CreateIndex
CREATE INDEX "twin_verifications_assetCode_status_idx" ON "twin_verifications"("assetCode", "status");

-- CreateIndex
CREATE INDEX "twin_verifications_status_horizonAt_idx" ON "twin_verifications"("status", "horizonAt");

-- CreateIndex
CREATE INDEX "twin_prediction_errors_verificationId_idx" ON "twin_prediction_errors"("verificationId");

-- CreateIndex
CREATE INDEX "twin_prediction_errors_channel_idx" ON "twin_prediction_errors"("channel");

-- CreateIndex
CREATE INDEX "verification_metrics_scopeKind_scopeCode_computedAt_idx" ON "verification_metrics"("scopeKind", "scopeCode", "computedAt");

-- CreateIndex
CREATE UNIQUE INDEX "physics_constraints_code_key" ON "physics_constraints"("code");

-- CreateIndex
CREATE INDEX "physics_constraints_kind_idx" ON "physics_constraints"("kind");

-- CreateIndex
CREATE INDEX "physics_constraints_scopeKind_scopeCode_idx" ON "physics_constraints"("scopeKind", "scopeCode");

-- CreateIndex
CREATE UNIQUE INDEX "physics_validation_runs_code_key" ON "physics_validation_runs"("code");

-- CreateIndex
CREATE INDEX "physics_validation_runs_subjectKind_subjectId_idx" ON "physics_validation_runs"("subjectKind", "subjectId");

-- CreateIndex
CREATE INDEX "physics_validation_runs_verdict_createdAt_idx" ON "physics_validation_runs"("verdict", "createdAt");

-- CreateIndex
CREATE INDEX "physics_checks_runId_idx" ON "physics_checks"("runId");

-- CreateIndex
CREATE INDEX "physics_checks_assetCode_idx" ON "physics_checks"("assetCode");

-- CreateIndex
CREATE INDEX "asset_operating_envelopes_assetCode_computedAt_idx" ON "asset_operating_envelopes"("assetCode", "computedAt");

-- CreateIndex
CREATE INDEX "uncertainty_estimates_subjectKind_subjectId_idx" ON "uncertainty_estimates"("subjectKind", "subjectId");

-- CreateIndex
CREATE INDEX "uncertainty_estimates_assetCode_computedAt_idx" ON "uncertainty_estimates"("assetCode", "computedAt");

-- CreateIndex
CREATE UNIQUE INDEX "discovery_runs_code_key" ON "discovery_runs"("code");

-- CreateIndex
CREATE INDEX "discovery_runs_objective_createdAt_idx" ON "discovery_runs"("objective", "createdAt");

-- CreateIndex
CREATE INDEX "discovery_runs_status_idx" ON "discovery_runs"("status");

-- CreateIndex
CREATE UNIQUE INDEX "scenario_discoveries_code_key" ON "scenario_discoveries"("code");

-- CreateIndex
CREATE INDEX "scenario_discoveries_runId_idx" ON "scenario_discoveries"("runId");

-- CreateIndex
CREATE INDEX "scenario_discoveries_status_riskScore_idx" ON "scenario_discoveries"("status", "riskScore");

-- CreateIndex
CREATE INDEX "discovery_conditions_discoveryId_idx" ON "discovery_conditions"("discoveryId");

-- CreateIndex
CREATE UNIQUE INDEX "adversarial_tests_code_key" ON "adversarial_tests"("code");

-- CreateIndex
CREATE INDEX "adversarial_tests_assetCode_createdAt_idx" ON "adversarial_tests"("assetCode", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "resilience_red_team_runs_code_key" ON "resilience_red_team_runs"("code");

-- CreateIndex
CREATE INDEX "resilience_red_team_runs_createdAt_idx" ON "resilience_red_team_runs"("createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "resilience_blue_team_runs_code_key" ON "resilience_blue_team_runs"("code");

-- CreateIndex
CREATE INDEX "resilience_blue_team_runs_redRunId_rank_idx" ON "resilience_blue_team_runs"("redRunId", "rank");

-- CreateIndex
CREATE INDEX "blue_team_actions_blueRunId_idx" ON "blue_team_actions"("blueRunId");

-- CreateIndex
CREATE UNIQUE INDEX "decision_memory_code_key" ON "decision_memory"("code");

-- CreateIndex
CREATE INDEX "decision_memory_assetCode_createdAt_idx" ON "decision_memory"("assetCode", "createdAt");

-- CreateIndex
CREATE INDEX "decision_memory_rootCauseKey_idx" ON "decision_memory"("rootCauseKey");

-- CreateIndex
CREATE INDEX "decision_memory_outcomeStatus_idx" ON "decision_memory"("outcomeStatus");

-- CreateIndex
CREATE INDEX "decision_outcomes_memoryId_idx" ON "decision_outcomes"("memoryId");

-- CreateIndex
CREATE INDEX "decision_lessons_memoryId_idx" ON "decision_lessons"("memoryId");

-- CreateIndex
CREATE UNIQUE INDEX "learning_candidates_code_key" ON "learning_candidates"("code");

-- CreateIndex
CREATE INDEX "learning_candidates_status_confidence_idx" ON "learning_candidates"("status", "confidence");

-- CreateIndex
CREATE INDEX "strategy_tradeoffs_runId_idx" ON "strategy_tradeoffs"("runId");

-- CreateIndex
CREATE INDEX "strategy_tradeoffs_strategyId_idx" ON "strategy_tradeoffs"("strategyId");

-- CreateIndex
CREATE INDEX "pareto_strategies_runId_rank_idx" ON "pareto_strategies"("runId", "rank");

-- CreateIndex
CREATE INDEX "cascade_probabilities_simulationId_depth_idx" ON "cascade_probabilities"("simulationId", "depth");

-- CreateIndex
CREATE INDEX "cascade_probabilities_assetCode_idx" ON "cascade_probabilities"("assetCode");

-- CreateIndex
CREATE INDEX "cascade_breakpoints_simulationId_isBest_idx" ON "cascade_breakpoints"("simulationId", "isBest");

-- CreateIndex
CREATE INDEX "evidence_nodes_bundleCode_orderIndex_idx" ON "evidence_nodes"("bundleCode", "orderIndex");

-- CreateIndex
CREATE INDEX "evidence_edges_bundleCode_idx" ON "evidence_edges"("bundleCode");

-- CreateIndex
CREATE INDEX "model_drift_events_modelKey_detectedAt_idx" ON "model_drift_events"("modelKey", "detectedAt");

-- CreateIndex
CREATE INDEX "model_drift_events_status_idx" ON "model_drift_events"("status");

-- CreateIndex
CREATE INDEX "data_provenance_subjectKind_subjectId_idx" ON "data_provenance"("subjectKind", "subjectId");

-- CreateIndex
CREATE INDEX "approval_records_subjectKind_subjectId_idx" ON "approval_records"("subjectKind", "subjectId");

-- CreateIndex
CREATE INDEX "approval_records_status_createdAt_idx" ON "approval_records"("status", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "compute_jobs_code_key" ON "compute_jobs"("code");

-- CreateIndex
CREATE INDEX "compute_jobs_kind_status_idx" ON "compute_jobs"("kind", "status");

-- CreateIndex
CREATE INDEX "compute_jobs_ownerId_createdAt_idx" ON "compute_jobs"("ownerId", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "integration_connectors_code_key" ON "integration_connectors"("code");

-- CreateIndex
CREATE INDEX "integration_connectors_kind_idx" ON "integration_connectors"("kind");

-- CreateIndex
CREATE INDEX "integration_connectors_status_idx" ON "integration_connectors"("status");

-- CreateIndex
CREATE INDEX "integration_mappings_connectorId_idx" ON "integration_mappings"("connectorId");

-- CreateIndex
CREATE UNIQUE INDEX "integration_mappings_connectorId_sourceField_key" ON "integration_mappings"("connectorId", "sourceField");

-- CreateIndex
CREATE INDEX "integration_events_connectorId_ts_idx" ON "integration_events"("connectorId", "ts");

-- CreateIndex
CREATE INDEX "integration_events_kind_idx" ON "integration_events"("kind");

-- CreateIndex
CREATE INDEX "integration_health_samples_connectorId_ts_idx" ON "integration_health_samples"("connectorId", "ts");

-- CreateIndex
CREATE UNIQUE INDEX "risk_preventions_code_key" ON "risk_preventions"("code");

-- CreateIndex
CREATE UNIQUE INDEX "risk_preventions_discoveryId_key" ON "risk_preventions"("discoveryId");

-- CreateIndex
CREATE INDEX "risk_preventions_assetCode_idx" ON "risk_preventions"("assetCode");

-- CreateIndex
CREATE INDEX "risk_prevention_doses_preventionId_idx" ON "risk_prevention_doses"("preventionId");

-- CreateIndex
CREATE UNIQUE INDEX "decision_proofs_code_key" ON "decision_proofs"("code");

-- CreateIndex
CREATE INDEX "decision_proofs_decisionId_idx" ON "decision_proofs"("decisionId");

-- CreateIndex
CREATE INDEX "decision_proofs_assetCode_createdAt_idx" ON "decision_proofs"("assetCode", "createdAt");

-- CreateIndex
CREATE INDEX "replay_events_proofId_seq_idx" ON "replay_events"("proofId", "seq");

-- AddForeignKey
ALTER TABLE "role_permissions" ADD CONSTRAINT "role_permissions_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "role_permissions" ADD CONSTRAINT "role_permissions_permissionId_fkey" FOREIGN KEY ("permissionId") REFERENCES "permissions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sites" ADD CONSTRAINT "sites_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_assetTypeId_fkey" FOREIGN KEY ("assetTypeId") REFERENCES "asset_types"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_siteId_fkey" FOREIGN KEY ("siteId") REFERENCES "sites"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "assets" ADD CONSTRAINT "assets_parentAssetId_fkey" FOREIGN KEY ("parentAssetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sensors" ADD CONSTRAINT "sensors_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sensor_readings" ADD CONSTRAINT "sensor_readings_sensorId_fkey" FOREIGN KEY ("sensorId") REFERENCES "sensors"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sensor_readings" ADD CONSTRAINT "sensor_readings_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "weather_data" ADD CONSTRAINT "weather_data_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "failure_patterns" ADD CONSTRAINT "failure_patterns_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "failure_patterns" ADD CONSTRAINT "failure_patterns_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "failure_dna" ADD CONSTRAINT "failure_dna_patternId_fkey" FOREIGN KEY ("patternId") REFERENCES "failure_patterns"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "model_audits" ADD CONSTRAINT "model_audits_modelVersionId_fkey" FOREIGN KEY ("modelVersionId") REFERENCES "model_versions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "predictions" ADD CONSTRAINT "predictions_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "predictions" ADD CONSTRAINT "predictions_modelVersionId_fkey" FOREIGN KEY ("modelVersionId") REFERENCES "model_versions"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "prediction_factors" ADD CONSTRAINT "prediction_factors_predictionId_fkey" FOREIGN KEY ("predictionId") REFERENCES "predictions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "recommendations" ADD CONSTRAINT "recommendations_predictionId_fkey" FOREIGN KEY ("predictionId") REFERENCES "predictions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "recommendations" ADD CONSTRAINT "recommendations_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "recommendations" ADD CONSTRAINT "recommendations_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "scenarios" ADD CONSTRAINT "scenarios_targetAssetId_fkey" FOREIGN KEY ("targetAssetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "scenarios" ADD CONSTRAINT "scenarios_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "simulations" ADD CONSTRAINT "simulations_scenarioId_fkey" FOREIGN KEY ("scenarioId") REFERENCES "scenarios"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "simulations" ADD CONSTRAINT "simulations_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "simulation_results" ADD CONSTRAINT "simulation_results_simulationId_fkey" FOREIGN KEY ("simulationId") REFERENCES "simulations"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "simulation_impacts" ADD CONSTRAINT "simulation_impacts_simulationId_fkey" FOREIGN KEY ("simulationId") REFERENCES "simulations"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "simulation_impacts" ADD CONSTRAINT "simulation_impacts_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "simulation_impacts" ADD CONSTRAINT "simulation_impacts_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "alerts" ADD CONSTRAINT "alerts_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "alerts" ADD CONSTRAINT "alerts_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "alerts" ADD CONSTRAINT "alerts_predictionId_fkey" FOREIGN KEY ("predictionId") REFERENCES "predictions"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "alerts" ADD CONSTRAINT "alerts_assignedToId_fkey" FOREIGN KEY ("assignedToId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "alerts" ADD CONSTRAINT "alerts_acknowledgedById_fkey" FOREIGN KEY ("acknowledgedById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "incidents" ADD CONSTRAINT "incidents_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "incidents" ADD CONSTRAINT "incidents_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "incident_events" ADD CONSTRAINT "incident_events_incidentId_fkey" FOREIGN KEY ("incidentId") REFERENCES "incidents"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "maintenance_records" ADD CONSTRAINT "maintenance_records_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "maintenance_records" ADD CONSTRAINT "maintenance_records_technicianId_fkey" FOREIGN KEY ("technicianId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "load_forecasts" ADD CONSTRAINT "load_forecasts_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "load_forecasts" ADD CONSTRAINT "load_forecasts_modelVersionId_fkey" FOREIGN KEY ("modelVersionId") REFERENCES "model_versions"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "renewable_forecasts" ADD CONSTRAINT "renewable_forecasts_regionId_fkey" FOREIGN KEY ("regionId") REFERENCES "regions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "renewable_forecasts" ADD CONSTRAINT "renewable_forecasts_siteId_fkey" FOREIGN KEY ("siteId") REFERENCES "sites"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "renewable_forecasts" ADD CONSTRAINT "renewable_forecasts_modelVersionId_fkey" FOREIGN KEY ("modelVersionId") REFERENCES "model_versions"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_alertId_fkey" FOREIGN KEY ("alertId") REFERENCES "alerts"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "demo_runs" ADD CONSTRAINT "demo_runs_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "grid_nodes" ADD CONSTRAINT "grid_nodes_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "grid_edges" ADD CONSTRAINT "grid_edges_fromNodeId_fkey" FOREIGN KEY ("fromNodeId") REFERENCES "grid_nodes"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "grid_edges" ADD CONSTRAINT "grid_edges_toNodeId_fkey" FOREIGN KEY ("toNodeId") REFERENCES "grid_nodes"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "agent_runs" ADD CONSTRAINT "agent_runs_agentId_fkey" FOREIGN KEY ("agentId") REFERENCES "ai_agents"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "agent_runs" ADD CONSTRAINT "agent_runs_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "agent_findings" ADD CONSTRAINT "agent_findings_runId_fkey" FOREIGN KEY ("runId") REFERENCES "agent_runs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "cascade_simulations" ADD CONSTRAINT "cascade_simulations_originAssetId_fkey" FOREIGN KEY ("originAssetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "cascade_steps" ADD CONSTRAINT "cascade_steps_simulationId_fkey" FOREIGN KEY ("simulationId") REFERENCES "cascade_simulations"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "counterfactual_runs" ADD CONSTRAINT "counterfactual_runs_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "counterfactual_actions" ADD CONSTRAINT "counterfactual_actions_runId_fkey" FOREIGN KEY ("runId") REFERENCES "counterfactual_runs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "strategies" ADD CONSTRAINT "strategies_optimizationId_fkey" FOREIGN KEY ("optimizationId") REFERENCES "optimization_runs"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "strategy_actions" ADD CONSTRAINT "strategy_actions_strategyId_fkey" FOREIGN KEY ("strategyId") REFERENCES "strategies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "strategy_results" ADD CONSTRAINT "strategy_results_strategyId_fkey" FOREIGN KEY ("strategyId") REFERENCES "strategies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "knowledge_edges" ADD CONSTRAINT "knowledge_edges_fromNodeId_fkey" FOREIGN KEY ("fromNodeId") REFERENCES "knowledge_nodes"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "knowledge_edges" ADD CONSTRAINT "knowledge_edges_toNodeId_fkey" FOREIGN KEY ("toNodeId") REFERENCES "knowledge_nodes"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "root_cause_analysis" ADD CONSTRAINT "root_cause_analysis_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sensor_trust_scores" ADD CONSTRAINT "sensor_trust_scores_sensorId_fkey" FOREIGN KEY ("sensorId") REFERENCES "sensors"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "decision_records" ADD CONSTRAINT "decision_records_strategyId_fkey" FOREIGN KEY ("strategyId") REFERENCES "strategies"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "approvals" ADD CONSTRAINT "approvals_decisionId_fkey" FOREIGN KEY ("decisionId") REFERENCES "decision_records"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "digital_twins" ADD CONSTRAINT "digital_twins_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_assets" ADD CONSTRAINT "twin_assets_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_assets" ADD CONSTRAINT "twin_assets_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "assets"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_states" ADD CONSTRAINT "twin_states_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_snapshots" ADD CONSTRAINT "twin_snapshots_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_sensor_bindings" ADD CONSTRAINT "twin_sensor_bindings_sensorId_fkey" FOREIGN KEY ("sensorId") REFERENCES "sensors"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_simulations" ADD CONSTRAINT "twin_simulations_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_simulations" ADD CONSTRAINT "twin_simulations_snapshotId_fkey" FOREIGN KEY ("snapshotId") REFERENCES "twin_snapshots"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_scenarios" ADD CONSTRAINT "twin_scenarios_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_events" ADD CONSTRAINT "twin_events_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_events" ADD CONSTRAINT "twin_events_scenarioId_fkey" FOREIGN KEY ("scenarioId") REFERENCES "twin_scenarios"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_deviations" ADD CONSTRAINT "twin_deviations_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_fidelity_scores" ADD CONSTRAINT "twin_fidelity_scores_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_versions" ADD CONSTRAINT "twin_versions_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "safe_operating_envelopes" ADD CONSTRAINT "safe_operating_envelopes_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "resilience_tests" ADD CONSTRAINT "resilience_tests_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "resilience_results" ADD CONSTRAINT "resilience_results_testId_fkey" FOREIGN KEY ("testId") REFERENCES "resilience_tests"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_verifications" ADD CONSTRAINT "twin_verifications_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "twin_prediction_errors" ADD CONSTRAINT "twin_prediction_errors_verificationId_fkey" FOREIGN KEY ("verificationId") REFERENCES "twin_verifications"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "physics_checks" ADD CONSTRAINT "physics_checks_runId_fkey" FOREIGN KEY ("runId") REFERENCES "physics_validation_runs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "physics_checks" ADD CONSTRAINT "physics_checks_constraintId_fkey" FOREIGN KEY ("constraintId") REFERENCES "physics_constraints"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "scenario_discoveries" ADD CONSTRAINT "scenario_discoveries_runId_fkey" FOREIGN KEY ("runId") REFERENCES "discovery_runs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "discovery_conditions" ADD CONSTRAINT "discovery_conditions_discoveryId_fkey" FOREIGN KEY ("discoveryId") REFERENCES "scenario_discoveries"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "adversarial_tests" ADD CONSTRAINT "adversarial_tests_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "resilience_red_team_runs" ADD CONSTRAINT "resilience_red_team_runs_twinId_fkey" FOREIGN KEY ("twinId") REFERENCES "digital_twins"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "resilience_blue_team_runs" ADD CONSTRAINT "resilience_blue_team_runs_redRunId_fkey" FOREIGN KEY ("redRunId") REFERENCES "resilience_red_team_runs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "blue_team_actions" ADD CONSTRAINT "blue_team_actions_blueRunId_fkey" FOREIGN KEY ("blueRunId") REFERENCES "resilience_blue_team_runs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "decision_outcomes" ADD CONSTRAINT "decision_outcomes_memoryId_fkey" FOREIGN KEY ("memoryId") REFERENCES "decision_memory"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "decision_lessons" ADD CONSTRAINT "decision_lessons_memoryId_fkey" FOREIGN KEY ("memoryId") REFERENCES "decision_memory"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "integration_mappings" ADD CONSTRAINT "integration_mappings_connectorId_fkey" FOREIGN KEY ("connectorId") REFERENCES "integration_connectors"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "integration_events" ADD CONSTRAINT "integration_events_connectorId_fkey" FOREIGN KEY ("connectorId") REFERENCES "integration_connectors"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "integration_health_samples" ADD CONSTRAINT "integration_health_samples_connectorId_fkey" FOREIGN KEY ("connectorId") REFERENCES "integration_connectors"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "risk_preventions" ADD CONSTRAINT "risk_preventions_discoveryId_fkey" FOREIGN KEY ("discoveryId") REFERENCES "scenario_discoveries"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "risk_prevention_doses" ADD CONSTRAINT "risk_prevention_doses_preventionId_fkey" FOREIGN KEY ("preventionId") REFERENCES "risk_preventions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "replay_events" ADD CONSTRAINT "replay_events_proofId_fkey" FOREIGN KEY ("proofId") REFERENCES "decision_proofs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

