import { db } from "../server/db";
import { threatEvents } from "../shared/schema";

const highFidelityAlerts = [
  {
    makerId: "LO-2847",
    checkerId: null,
    amount: "0",
    currency: "UGX",
    threatType: "AFTER_HOURS" as const,
    riskLevel: "CRITICAL" as const,
    terminalIp: "10.42.8.156",
    branch: "Kampala-Central",
    description: JSON.stringify({
      title: "The Dormant Volcano",
      narrative: "Junior Loan Officer (LO-2847) logged in at 23:31 EAT and attempted bulk query of 547 High-Net-Worth customer profiles. Officer has not accessed these tables in 6 months. Pattern indicates potential insider reconnaissance.",
      aiLogic: ["Behavioral Drift Detection", "Privilege Escalation Attempt", "After-Hours Access Anomaly"],
      actionTaken: "Session locked immediately; MFA challenge sent to Branch Manager (BM-0012); Security team notified via SMS gateway.",
      affectedProfiles: 547,
      lastNormalAccess: "2025-07-24T14:22:00Z",
      riskIndicators: ["11:31 PM access (vs. normal 9-5 pattern)", "Bulk HNW profile query", "6-month dormancy on sensitive tables"],
      reasoningText: "Access pattern for LO-2847 shows a 4.2-sigma deviation from established baseline. Historical access confined to 09:00-17:00 EAT window with mean query volume of 12 records/session. Current session initiated at 23:31 EAT with 547 HNW profile queries in first 4 minutes. Dormancy coefficient on CUSTOMER_HNW table exceeded 180-day threshold. Cross-referencing with HR database shows no scheduled overtime authorization.",
      visualizationType: "heatmap",
      sigmaDeviation: 4.2
    }),
    anomalyScore: "0.9847",
    featureContributions: JSON.stringify({
      timeOfAccess: 0.35,
      queryVolume: 0.28,
      dormancyPeriod: 0.22,
      sensitiveTableAccess: 0.15
    })
  },
  {
    makerId: "CM-1104",
    checkerId: null,
    amount: "0",
    currency: "UGX",
    threatType: "GEO_ANOMALY" as const,
    riskLevel: "HIGH" as const,
    terminalIp: "185.244.25.187",
    branch: "Frankfurt-Proxy",
    description: JSON.stringify({
      title: "The Ghost Login",
      narrative: "Corporate Manager (CM-1104) successful login from Kampala IP (41.210.x.x), but simultaneous API request detected using same credentials from Frankfurt hosting provider (185.244.25.187). Impossible travel detected - 6,400km in 0 seconds.",
      aiLogic: ["Impossible Travel Detection", "High-Entropy IP Analysis", "Concurrent Session Anomaly"],
      actionTaken: "Frankfurt session terminated immediately; Account marked for Shadow Monitoring; mTLS certificate revoked for remote session.",
      legitimateLocation: "Kampala, Uganda",
      anomalousLocation: "Frankfurt, Germany",
      distanceKm: 6412,
      timeDelta: "0 seconds",
      riskIndicators: ["Simultaneous logins from 2 continents", "Hosting provider IP (not residential)", "API access pattern mismatch"],
      reasoningText: "Geo-velocity calculation triggered impossibility threshold. Session A originated from AS37063 (MTN Uganda) at coordinates 0.3476°N, 32.5825°E. Session B API call from AS24940 (Hetzner Online GmbH) at 50.1109°N, 8.6821°E. Distance: 6,412km. Time delta: 0.003 seconds. Required velocity: 7.7×10⁹ km/h (impossible). IP 185.244.25.187 flagged in threat intelligence as hosting provider commonly used for credential stuffing infrastructure.",
      visualizationType: "worldmap",
      requiredVelocity: "7.7×10⁹ km/h"
    }),
    anomalyScore: "0.9234",
    featureContributions: JSON.stringify({
      impossibleTravel: 0.42,
      ipEntropy: 0.28,
      concurrentSessions: 0.20,
      apiPatternDeviation: 0.10
    })
  },
  {
    makerId: "MK-3391",
    checkerId: null,
    amount: "10000000",
    currency: "UGX",
    threatType: "VELOCITY_BREACH" as const,
    riskLevel: "CRITICAL" as const,
    terminalIp: "10.42.12.89",
    branch: "Jinja-Branch",
    description: JSON.stringify({
      title: "The Rapid-Fire Maker",
      narrative: "Data Entry Maker (MK-3391) initiated 20 transfers of UGX 500,000 each to different mobile money wallets within 60 seconds. All 20 recipient wallets were created in the last 24 hours. Total exposure: UGX 10,000,000.",
      aiLogic: ["Transaction Velocity Anomaly", "Synthetic Identity Linkage", "New Wallet Burst Pattern"],
      actionTaken: "Outbound transfer queue paused; Maker-Checker privileges suspended; Compliance alert generated for AML desk.",
      transferCount: 20,
      amountPerTransfer: 500000,
      timeWindowSeconds: 60,
      newWalletAge: "< 24 hours",
      riskIndicators: ["20 transfers in 60 seconds", "All recipients are new wallets", "Structuring pattern detected (sub-threshold amounts)"],
      reasoningText: "Transaction velocity exceeded safe threshold by 847%. Maker MK-3391 average historical throughput: 2.1 transactions/minute. Current burst: 20 transactions/minute. All 20 recipient wallets share creation timestamp within 18-hour window. Graph analysis reveals shared device fingerprint across 14/20 wallets (IMEI cluster detected). Amount structuring pattern: all transactions precisely UGX 500,000 (below UGX 1M reporting threshold). Probability of legitimate batch: 0.003%.",
      visualizationType: "velocitySpike",
      velocityExceeded: "847%"
    }),
    anomalyScore: "0.9712",
    featureContributions: JSON.stringify({
      transactionVelocity: 0.38,
      recipientAge: 0.32,
      amountStructuring: 0.18,
      burstPattern: 0.12
    })
  },
  {
    makerId: "DBA-0156",
    checkerId: null,
    amount: "0",
    currency: "UGX",
    threatType: "BULK_ACCESS" as const,
    riskLevel: "HIGH" as const,
    terminalIp: "10.42.1.22",
    branch: "HQ-DataCenter",
    description: JSON.stringify({
      title: "The Slow Leak",
      narrative: "Database Administrator (DBA-0156) running daily 'backup' jobs that are consistently 2.3% larger than expected. Forensic analysis reveals customer National ID numbers hidden in encrypted blobs within backup files.",
      aiLogic: ["Data Volume Divergence", "Protocol Tunneling Detection", "Steganographic Pattern Analysis"],
      actionTaken: "Alert generated for PDPO Form 7 breach report; Forensic log-chaining initiated; DBA access restricted to read-only pending investigation.",
      backupSizeDeviation: "2.3%",
      detectedDataTypes: ["National ID Numbers", "Phone Numbers", "Account Balances"],
      exfiltrationMethod: "Encrypted blob injection in backup stream",
      riskIndicators: ["Consistent 2%+ backup size deviation", "Encrypted blobs in unencrypted backup", "Customer PII detected in exports"],
      reasoningText: "Backup volume analysis detected persistent deviation. Expected daily backup size: 847.2 GB ± 0.3%. Actual size over 14-day window: 866.7 GB (avg +2.3% deviation). Entropy analysis of 'config_blob' field shows encrypted payload embedded in standard backup stream. Decrypted sample contains 12,847 customer National ID numbers in Base64-encoded format. Data lineage tracking shows DBA-0156 as sole accessor of backup encryption keys. Exfiltration vector: SFTP to external IP masked as 'offsite backup mirror'.",
      visualizationType: "volumeDeviation",
      deviationPercent: "2.3%"
    }),
    anomalyScore: "0.8956",
    featureContributions: JSON.stringify({
      dataSizeAnomaly: 0.35,
      protocolDeviation: 0.30,
      piiDetection: 0.25,
      accessFrequency: 0.10
    })
  },
  {
    makerId: "CUST-847291",
    checkerId: null,
    amount: "45000000",
    currency: "UGX",
    threatType: "INTERNAL_XFER" as const,
    riskLevel: "MEDIUM" as const,
    terminalIp: "External-ATM",
    branch: "Mbarara-ATM-Network",
    description: JSON.stringify({
      title: "The Mule-Train",
      narrative: "Elderly customer account (CUST-847291, age 72) typically sees 2 transactions/month. In the last 4 hours: received 5 large inbound wires totaling UGX 45,000,000, followed by immediate ATM withdrawals in Mbarara (300km from home address in Kampala).",
      aiLogic: ["Account Takeover Pattern", "Social Engineering Victim Profile", "Geographic Withdrawal Anomaly"],
      actionTaken: "Account placed in Safety Hold; Automated outbound voice-verification call triggered to registered phone; Branch manager alerted for customer welfare check.",
      customerAge: 72,
      normalTransactionsPerMonth: 2,
      inboundWireCount: 5,
      totalInbound: 45000000,
      withdrawalLocation: "Mbarara",
      homeLocation: "Kampala",
      distanceFromHome: "300km",
      riskIndicators: ["Sudden 5x wire activity spike", "Immediate ATM withdrawal pattern", "300km geographic deviation", "Elderly customer profile (ATO target)"],
      reasoningText: "Behavioral DNA analysis triggered social engineering alert. Customer CUST-847291 baseline profile: age 72, pension account, 2.1 transactions/month average, all activity within 5km of Kampala residence. Current anomaly: 5 inbound SWIFT transfers from 3 different originating banks within 4-hour window, followed by 3 ATM withdrawals at Mbarara (296km from home). Withdrawal velocity suggests urgency coaching. Pattern matches 'Romance Scam/Grandparent Scam' ATO template with 94.2% confidence. Voice stress analysis on prior call recording shows elevated anxiety markers.",
      visualizationType: "behavioralDna",
      patternMatch: "Romance Scam/Grandparent Scam",
      matchConfidence: "94.2%"
    }),
    anomalyScore: "0.8723",
    featureContributions: JSON.stringify({
      activitySpike: 0.32,
      atoProfileMatch: 0.28,
      geographicDeviation: 0.25,
      immediateWithdrawal: 0.15
    })
  }
];

async function seedHighFidelityAlerts() {
  console.log("🚀 Seeding High-Fidelity Banking Threat Scenarios...\n");

  for (const alert of highFidelityAlerts) {
    const parsed = JSON.parse(alert.description);
    console.log(`📍 Inserting: ${parsed.title}`);
    console.log(`   Risk Level: ${alert.riskLevel}`);
    console.log(`   Confidence Score: ${alert.anomalyScore}`);
    console.log(`   Action: ${parsed.actionTaken.substring(0, 60)}...`);
    
    await db.insert(threatEvents).values(alert);
    console.log("   ✅ Inserted\n");
  }

  console.log("🎯 All 5 High-Fidelity Alerts seeded successfully!");
  console.log("\n📊 Summary:");
  console.log("   - 2x CRITICAL (P1)");
  console.log("   - 2x HIGH (P2)");
  console.log("   - 1x MEDIUM (P3)");
  console.log("\n💡 Demo Tip: Click any alert to view the 'AI Reasoning' tab with behavioral graphs.");
  
  process.exit(0);
}

seedHighFidelityAlerts().catch((err) => {
  console.error("❌ Seed failed:", err);
  process.exit(1);
});
