// =============================================================================
// APOPHIS SOC - Mock Data Generators
// Generates realistic-looking security operations data for the dashboard
// =============================================================================

const ATTACK_TYPES = [
  'SSH Brute Force', 'SQL Injection', 'XSS Attempt', 'Port Scan',
  'DNS Tunneling', 'C2 Beacon', 'Credential Stuffing', 'DDoS SYN Flood',
  'Malware Download', 'Privilege Escalation', 'Lateral Movement',
  'Data Exfiltration', 'Phishing Link Click', 'RDP Brute Force',
  'SMB Exploit', 'ARP Spoofing', 'ICMP Flood', 'Directory Traversal',
  'Buffer Overflow', 'Zero-Day Exploit'
];

const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
const SEVERITY_WEIGHTS = [0.05, 0.15, 0.35, 0.30, 0.15];

const SOURCES = [
  'Suricata IDS', 'pfSense Firewall', 'Wazuh SIEM', 'ClamAV',
  'Zeek Network Monitor', 'OSSEC HIDS', 'Fail2Ban', 'Snort IPS',
  'ModSecurity WAF', 'OpenVAS Scanner'
];

const COUNTRIES = [
  { code: 'CN', name: 'China', weight: 0.20 },
  { code: 'RU', name: 'Russia', weight: 0.18 },
  { code: 'US', name: 'United States', weight: 0.12 },
  { code: 'KP', name: 'North Korea', weight: 0.08 },
  { code: 'IR', name: 'Iran', weight: 0.07 },
  { code: 'BR', name: 'Brazil', weight: 0.07 },
  { code: 'IN', name: 'India', weight: 0.06 },
  { code: 'DE', name: 'Germany', weight: 0.05 },
  { code: 'NL', name: 'Netherlands', weight: 0.05 },
  { code: 'RO', name: 'Romania', weight: 0.04 },
  { code: 'UA', name: 'Ukraine', weight: 0.04 },
  { code: 'VN', name: 'Vietnam', weight: 0.04 },
];

const MITRE_TACTICS = [
  'Reconnaissance', 'Resource Dev', 'Initial Access', 'Execution',
  'Persistence', 'Priv Escalation', 'Defense Evasion', 'Credential Access',
  'Discovery', 'Lateral Movement', 'Collection', 'C2', 'Exfiltration', 'Impact'
];

const MITRE_TECHNIQUES = {
  'Reconnaissance': ['Active Scanning', 'Search Open Websites', 'Gather Victim Info', 'Phishing for Info'],
  'Resource Dev': ['Acquire Infrastructure', 'Develop Capabilities', 'Stage Capabilities', 'Compromise Accounts'],
  'Initial Access': ['Phishing', 'Exploit Public App', 'Valid Accounts', 'Drive-by Compromise'],
  'Execution': ['Command & Script', 'Scheduled Task', 'User Execution', 'WMI'],
  'Persistence': ['Boot Autostart', 'Create Account', 'Scheduled Task', 'Server Software'],
  'Priv Escalation': ['Abuse Elevation', 'Access Token', 'Boot Autostart', 'Exploitation'],
  'Defense Evasion': ['Obfuscation', 'Masquerading', 'Rootkit', 'Process Injection'],
  'Credential Access': ['Brute Force', 'OS Credential Dump', 'Keylogging', 'Network Sniffing'],
  'Discovery': ['Account Discovery', 'Network Scan', 'System Info', 'Process Discovery'],
  'Lateral Movement': ['Remote Services', 'SMB/Admin Share', 'Pass the Hash', 'RDP'],
  'Collection': ['Data from Local', 'Screen Capture', 'Clipboard Data', 'Email Collection'],
  'C2': ['Application Layer', 'Encrypted Channel', 'Proxy', 'Web Service'],
  'Exfiltration': ['Exfil Over C2', 'Exfil Over Web', 'Automated Exfil', 'Transfer Size Limits'],
  'Impact': ['Data Destruction', 'Data Encrypted', 'Service Stop', 'Defacement'],
};

// --- Utility functions ---

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

function randomChoice(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function weightedChoice(items, weights) {
  const r = Math.random();
  let sum = 0;
  for (let i = 0; i < items.length; i++) {
    sum += weights[i];
    if (r <= sum) return items[i];
  }
  return items[items.length - 1];
}

function randomIP() {
  // Generate realistic-looking external IPs (avoiding private ranges)
  const firstOctet = randomChoice([1, 2, 5, 14, 23, 31, 37, 41, 45, 46, 49, 58, 59, 60, 61, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 103, 104, 106, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223]);
  return `${firstOctet}.${randomInt(1, 254)}.${randomInt(1, 254)}.${randomInt(1, 254)}`;
}

let alertIdCounter = 1000;

// --- Public API ---

export function generateAlert() {
  const severity = weightedChoice(SEVERITIES, SEVERITY_WEIGHTS);
  const country = weightedChoice(
    COUNTRIES.map(c => c),
    COUNTRIES.map(c => c.weight)
  );
  return {
    id: `APH-${String(alertIdCounter++).padStart(5, '0')}`,
    timestamp: new Date(),
    severity,
    attackType: randomChoice(ATTACK_TYPES),
    sourceIP: randomIP(),
    targetIP: `10.0.${randomInt(1, 5)}.${randomInt(1, 254)}`,
    source: randomChoice(SOURCES),
    country: country.code,
    countryName: country.name,
    port: randomChoice([22, 80, 443, 445, 3389, 8080, 8443, 3306, 5432, 53, 25, 110, 143, 993, 995]),
    blocked: Math.random() > 0.3,
  };
}

export function generateAlertBatch(count = 20) {
  const alerts = [];
  for (let i = 0; i < count; i++) {
    const alert = generateAlert();
    alert.timestamp = new Date(Date.now() - randomInt(0, 3600000));
    alerts.push(alert);
  }
  return alerts.sort((a, b) => b.timestamp - a.timestamp);
}

export function generateTrafficData(points = 24) {
  const data = [];
  const now = new Date();
  for (let i = points - 1; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 3600000);
    const hour = time.getHours();
    // Simulate higher traffic during business hours
    const multiplier = (hour >= 8 && hour <= 18) ? 1.5 : (hour >= 0 && hour <= 5) ? 0.4 : 1.0;
    data.push({
      time: time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      inbound: Math.round(randomFloat(120, 450) * multiplier),
      outbound: Math.round(randomFloat(80, 320) * multiplier),
      blocked: Math.round(randomFloat(5, 60) * multiplier),
    });
  }
  return data;
}

export function generateSystemHealth() {
  return [
    { name: 'pfSense Firewall', status: Math.random() > 0.05 ? 'online' : 'warning', cpu: randomInt(8, 45), mem: randomInt(30, 70), uptime: `${randomInt(10, 90)}d` },
    { name: 'Suricata IDS', status: Math.random() > 0.08 ? 'online' : 'warning', cpu: randomInt(15, 65), mem: randomInt(40, 80), uptime: `${randomInt(5, 60)}d` },
    { name: 'Wazuh SIEM', status: Math.random() > 0.05 ? 'online' : 'warning', cpu: randomInt(20, 55), mem: randomInt(50, 85), uptime: `${randomInt(3, 45)}d` },
    { name: 'ClamAV Scanner', status: Math.random() > 0.10 ? 'online' : 'offline', cpu: randomInt(5, 30), mem: randomInt(20, 50), uptime: `${randomInt(1, 30)}d` },
    { name: 'Zeek Monitor', status: Math.random() > 0.05 ? 'online' : 'warning', cpu: randomInt(10, 50), mem: randomInt(35, 75), uptime: `${randomInt(7, 60)}d` },
    { name: 'OpenVAS', status: Math.random() > 0.12 ? 'online' : 'offline', cpu: randomInt(5, 25), mem: randomInt(15, 45), uptime: `${randomInt(2, 20)}d` },
  ];
}

export function generateMitreData() {
  const data = {};
  for (const tactic of MITRE_TACTICS) {
    data[tactic] = {};
    for (const technique of MITRE_TECHNIQUES[tactic]) {
      // 0 = not seen, 1 = low, 2 = medium, 3 = high detection count
      data[tactic][technique] = Math.random() > 0.4 ? randomInt(0, 3) : 0;
    }
  }
  return data;
}

export function generateTopThreats(count = 8) {
  const threats = [];
  const usedIPs = new Set();
  for (let i = 0; i < count; i++) {
    let ip;
    do { ip = randomIP(); } while (usedIPs.has(ip));
    usedIPs.add(ip);
    const country = weightedChoice(
      COUNTRIES.map(c => c),
      COUNTRIES.map(c => c.weight)
    );
    threats.push({
      ip,
      country: country.code,
      countryName: country.name,
      attackType: randomChoice(ATTACK_TYPES),
      count: randomInt(15, 500),
      lastSeen: new Date(Date.now() - randomInt(0, 7200000)),
      blocked: Math.random() > 0.2,
    });
  }
  return threats.sort((a, b) => b.count - a.count);
}

export function generateIncidents() {
  const statuses = ['Open', 'Investigating', 'Contained', 'Resolved'];
  const priorities = ['P1', 'P2', 'P3', 'P4'];
  const descriptions = [
    'Suspicious outbound C2 traffic detected on endpoint WS-04',
    'Multiple failed SSH logins from external IP on DMZ server',
    'Malware signature detected in email attachment',
    'Unauthorized port scan from internal host 10.0.2.15',
    'Privilege escalation attempt on domain controller',
    'Data exfiltration alert: large DNS TXT queries',
    'Brute force attack on VPN gateway',
    'Phishing campaign targeting finance department',
    'Anomalous lateral movement between VLANs',
    'Ransomware indicator detected on file server',
  ];
  return descriptions.slice(0, randomInt(4, 8)).map((desc, i) => ({
    id: `INC-${String(2024001 + i).padStart(7, '0')}`,
    description: desc,
    status: i === 0 ? 'Open' : randomChoice(statuses),
    priority: i < 2 ? priorities[i] : randomChoice(priorities),
    assignee: randomChoice(['analyst-1', 'analyst-2', 'lead-soc', 'ir-team']),
    created: new Date(Date.now() - randomInt(3600000, 86400000 * 3)),
  }));
}

export function generateVulnSummary() {
  return {
    critical: randomInt(2, 8),
    high: randomInt(10, 35),
    medium: randomInt(25, 80),
    low: randomInt(40, 120),
    info: randomInt(50, 200),
  };
}

export function getOverallThreatLevel(alerts) {
  const critCount = alerts.filter(a => a.severity === 'critical').length;
  const highCount = alerts.filter(a => a.severity === 'high').length;
  if (critCount >= 3) return 'CRITICAL';
  if (critCount >= 1 || highCount >= 5) return 'HIGH';
  if (highCount >= 2) return 'ELEVATED';
  return 'GUARDED';
}

export { MITRE_TACTICS, MITRE_TECHNIQUES, SEVERITIES };
