/**
 * Playbook Generator - Creates v2 format playbooks for alert investigations
 * 
 * V2 playbooks include:
 * - playbook_version: 2
 * - artifacts: Array with OSINT simulation data (extracted from raw log)
 * - expected_actions: Array of action IDs
 * - expected_verdict: The correct verdict
 * - expected_category: Attack category
 * 
 * ROBUST VERSION: Parses raw log to extract actual indicators and generate
 * consistent OSINT results based on the real alert data.
 */

/**
 * Check if an IP is private/internal (RFC 1918, loopback, link-local)
 */
const isPrivateIP = (ip) => {
    if (!ip || typeof ip !== 'string') return false;

    const parts = ip.split('.').map(Number);
    if (parts.length !== 4 || parts.some(p => isNaN(p) || p < 0 || p > 255)) return false;

    // 10.0.0.0 - 10.255.255.255 (Class A private)
    if (parts[0] === 10) return true;

    // 172.16.0.0 - 172.31.255.255 (Class B private)
    if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;

    // 192.168.0.0 - 192.168.255.255 (Class C private)
    if (parts[0] === 192 && parts[1] === 168) return true;

    // 127.0.0.0 - 127.255.255.255 (Loopback)
    if (parts[0] === 127) return true;

    // 169.254.0.0 - 169.254.255.255 (Link-local)
    if (parts[0] === 169 && parts[1] === 254) return true;

    // 0.0.0.0 (Invalid/unspecified)
    if (parts.every(p => p === 0)) return true;

    return false;
};

/**
 * Extract indicators from raw log JSON
 */
const extractIndicatorsFromRawLog = (rawLog) => {
    const indicators = {
        ips: [],
        usernames: [],
        domains: [],
        urls: [],
        hashes: [],
        emails: [],
        filenames: [],
        locations: [],
        ports: [],
        sqlPayloads: [],      // NEW: SQL injection patterns
        targetDomains: [],    // NEW: Domains that are targets, not attackers
        failedAttempts: 0,
        eventType: null,
        additionalContext: {}
    };

    if (!rawLog) return indicators;

    // Parse raw log if it's a string
    let logData = rawLog;
    if (typeof rawLog === 'string') {
        try {
            logData = JSON.parse(rawLog);
        } catch (e) {
            // If not valid JSON, try to extract patterns from text
            return extractFromText(rawLog);
        }
    }

    // Extract from structured log
    const extractRecursive = (obj, path = '') => {
        if (!obj || typeof obj !== 'object') return;

        for (const [key, value] of Object.entries(obj)) {
            const keyLower = key.toLowerCase();

            if (typeof value === 'string') {
                // IP addresses
                if (keyLower.includes('ip') || keyLower.includes('address') || keyLower.includes('src') || keyLower.includes('dst')) {
                    const ipMatch = value.match(/\b(?:\d{1,3}\.){3}\d{1,3}\b/);
                    if (ipMatch && !indicators.ips.find(i => i.value === ipMatch[0])) {
                        indicators.ips.push({ value: ipMatch[0], field: key });
                    }
                }

                // Usernames
                if (keyLower.includes('user') || keyLower.includes('account') || keyLower.includes('login')) {
                    if (!value.includes('@') && !value.includes('.') && value.length > 0 && value.length < 50) {
                        if (!indicators.usernames.find(u => u.value === value)) {
                            indicators.usernames.push({ value, field: key });
                        }
                    }
                }

                // Emails
                const emailMatch = value.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/);
                if (emailMatch && !indicators.emails.find(e => e.value === emailMatch[0])) {
                    indicators.emails.push({ value: emailMatch[0], field: key });
                }

                // Domains - check if it's from Host header (target site, not attacker)
                if (keyLower.includes('domain') || keyLower.includes('host') || keyLower.includes('url')) {
                    const domainMatch = value.match(/(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/);
                    if (domainMatch && !domainMatch[0].includes('@')) {
                        const isHostHeader = keyLower === 'host' || keyLower.includes('header');
                        if (isHostHeader) {
                            // Host header = target site, not attacker
                            if (!indicators.targetDomains.find(d => d.value === domainMatch[0])) {
                                indicators.targetDomains.push({ value: domainMatch[0], field: key, isTarget: true });
                            }
                        } else {
                            if (!indicators.domains.find(d => d.value === domainMatch[0])) {
                                indicators.domains.push({ value: domainMatch[0], field: key });
                            }
                        }
                    }
                }

                // SQL Injection patterns in request body/query
                if (keyLower.includes('body') || keyLower.includes('query') || keyLower.includes('request') || keyLower.includes('param')) {
                    const sqlPatterns = [
                        /('|")?\s*(OR|AND)\s+('|")?[\d\w]+('|")?\s*=\s*('|")?[\d\w]+('|")?/gi,  // OR 1=1
                        /('\s*--|\s*--\s*$)/gi,                                                    // SQL comment
                        /UNION\s+(ALL\s+)?SELECT/gi,                                               // UNION SELECT
                        /(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER)\s+/gi,                   // SQL keywords
                        /;\s*(SELECT|INSERT|UPDATE|DELETE|DROP)/gi,                               // Stacked queries
                        /WAITFOR\s+DELAY/gi,                                                       // Time-based SQLi
                        /SLEEP\s*\(/gi,                                                            // MySQL sleep
                        /BENCHMARK\s*\(/gi,                                                        // MySQL benchmark
                        /EXEC(\s+|\()xp_/gi,                                                       // xp_ procedures
                    ];

                    for (const pattern of sqlPatterns) {
                        const match = value.match(pattern);
                        if (match && !indicators.sqlPayloads.find(s => s.value === match[0])) {
                            indicators.sqlPayloads.push({ value: match[0], field: key, fullValue: value });
                            break; // Only need one match per field
                        }
                    }
                }

                // URLs
                if (value.startsWith('http://') || value.startsWith('https://')) {
                    if (!indicators.urls.find(u => u.value === value)) {
                        indicators.urls.push({ value, field: key });
                    }
                }

                // Hashes (MD5, SHA1, SHA256)
                if (keyLower.includes('hash') || keyLower.includes('md5') || keyLower.includes('sha')) {
                    const hashMatch = value.match(/\b[a-fA-F0-9]{32,64}\b/);
                    if (hashMatch && !indicators.hashes.find(h => h.value === hashMatch[0])) {
                        indicators.hashes.push({ value: hashMatch[0], field: key });
                    }
                }

                // Filenames
                if (keyLower.includes('file') || keyLower.includes('path') || keyLower.includes('name')) {
                    const fileMatch = value.match(/[\w.-]+\.(exe|dll|ps1|bat|vbs|js|py|sh|bin|msi|jar|doc|docx|xls|xlsx|pdf|zip|rar)$/i);
                    if (fileMatch && !indicators.filenames.find(f => f.value === value)) {
                        indicators.filenames.push({ value, field: key });
                    }
                }

                // Location/Country
                if (keyLower.includes('location') || keyLower.includes('country') || keyLower.includes('geo') || keyLower.includes('region')) {
                    if (!indicators.locations.find(l => l.value === value)) {
                        indicators.locations.push({ value, field: key });
                    }
                }

                // Event type
                if (keyLower.includes('event') || keyLower.includes('action') || keyLower.includes('type')) {
                    indicators.eventType = value;
                }
            } else if (typeof value === 'number') {
                // Failed attempts count
                if (keyLower.includes('fail') || keyLower.includes('attempt') || keyLower.includes('count')) {
                    indicators.failedAttempts = Math.max(indicators.failedAttempts, value);
                }
                // Port numbers
                if (keyLower.includes('port')) {
                    if (!indicators.ports.find(p => p.value === value)) {
                        indicators.ports.push({ value: String(value), field: key });
                    }
                }
            } else if (typeof value === 'object' && value !== null) {
                extractRecursive(value, `${path}.${key}`);
            }
        }
    };

    extractRecursive(logData);

    // Store additional context
    indicators.additionalContext = {
        rawEventType: logData.event_type || logData.eventType || logData.action,
        severity: logData.severity || logData.priority,
        timestamp: logData.timestamp || logData.time,
        source: logData.source || logData.src,
        destination: logData.destination || logData.dst
    };

    return indicators;
};

/**
 * Extract indicators from plain text (fallback)
 */
const extractFromText = (text) => {
    const indicators = {
        ips: [],
        usernames: [],
        domains: [],
        urls: [],
        hashes: [],
        emails: [],
        filenames: [],
        locations: [],
        ports: [],
        failedAttempts: 0,
        eventType: null,
        additionalContext: {}
    };

    // Extract IPs
    const ipMatches = text.match(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g) || [];
    ipMatches.forEach(ip => {
        if (!indicators.ips.find(i => i.value === ip)) {
            indicators.ips.push({ value: ip, field: 'extracted' });
        }
    });

    // Extract emails
    const emailMatches = text.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g) || [];
    emailMatches.forEach(email => {
        if (!indicators.emails.find(e => e.value === email)) {
            indicators.emails.push({ value: email, field: 'extracted' });
        }
    });

    // Extract hashes
    const hashMatches = text.match(/\b[a-fA-F0-9]{32,64}\b/g) || [];
    hashMatches.forEach(hash => {
        if (!indicators.hashes.find(h => h.value === hash)) {
            indicators.hashes.push({ value: hash, field: 'extracted' });
        }
    });

    return indicators;
};

/**
 * Determine if the scenario is malicious based on indicators
 */
const analyzeIndicators = (indicators, alertType, severity, title) => {
    const analysis = {
        isMalicious: false,
        confidence: 'medium',
        reasons: [],
        category: 'unknown'
    };

    const contextString = (alertType + ' ' + title).toLowerCase();

    // High severity usually indicates malicious
    const severityLower = (severity || '').toLowerCase();
    if (severityLower === 'critical' || severityLower === 'high') {
        analysis.isMalicious = true;
        analysis.confidence = 'high';
        analysis.reasons.push(`High/Critical severity level`);
    }

    // Multiple failed login attempts (brute force indicator)
    if (indicators.failedAttempts >= 5) {
        analysis.isMalicious = true;
        analysis.reasons.push(`${indicators.failedAttempts} failed login attempts detected`);
        analysis.category = 'credential_attack';
    }

    // Suspicious locations
    const suspiciousCountries = ['russia', 'china', 'north korea', 'iran', 'nigeria', 'romania', 'ukraine', 'belarus'];
    indicators.locations.forEach(loc => {
        if (suspiciousCountries.some(c => loc.value.toLowerCase().includes(c))) {
            analysis.isMalicious = true;
            analysis.reasons.push(`Suspicious origin country: ${loc.value}`);
        }
    });

    // Title/type based analysis
    if (contextString.match(/malware|ransomware|trojan|virus|c2|command.*control|beacon|backdoor|shell|meterpreter/)) {
        analysis.isMalicious = true;
        analysis.category = 'malware';
        analysis.reasons.push('Alert type indicates malware/C2 activity');
    }

    if (contextString.match(/powershell|cmd|script|obfuscat|encoded|execution|bypass/)) {
        analysis.isMalicious = true;
        analysis.category = 'malware';
        analysis.reasons.push('Alert type indicates suspicious script execution');
    }

    if (contextString.match(/phishing|credential.harvest|fake.login|spam|suspicious.email/)) {
        analysis.isMalicious = true;
        analysis.category = 'phishing';
        analysis.reasons.push('Alert type indicates phishing');
    }

    if (contextString.match(/brute.?force|failed.login|auth.*fail|password.*spray|access.denied/)) {
        analysis.isMalicious = true;
        analysis.category = 'credential_attack';
        analysis.reasons.push('Alert type indicates credential attack');
    }

    if (contextString.match(/sql.*inject|xss|rce|lfi|rfi|web.*attack|cross.site|directory.traversal/)) {
        analysis.isMalicious = true;
        analysis.category = 'web_attack';
        analysis.reasons.push('Alert type indicates web application attack');
    }

    if (contextString.match(/exfil|data.*leak|sensitive.*data|upload/)) {
        analysis.isMalicious = true;
        analysis.category = 'data_exfiltration';
        analysis.reasons.push('Alert type indicates data exfiltration');
    }

    if (contextString.match(/lateral.*move|psexec|wmi.*remote|smb.*spread|remote.execution/)) {
        analysis.isMalicious = true;
        analysis.category = 'lateral_movement';
        analysis.reasons.push('Alert type indicates lateral movement');
    }

    // Low severity with no other indicators = likely false positive
    if (severity === 'Low' && analysis.reasons.length === 0) {
        analysis.isMalicious = false;
        analysis.confidence = 'high';
        analysis.reasons.push('Low severity with no suspicious indicators');
    }

    // Medium severity is 50/50 unless other indicators present
    if (severity === 'Medium' && analysis.reasons.length === 0) {
        analysis.isMalicious = Math.random() > 0.5;
        analysis.confidence = 'medium';
    }

    return analysis;
};

/**
 * Generate OSINT result for an artifact based on analysis
 */
const generateOSINTResult = (artifactType, artifactValue, isMalicious, context = {}) => {
    // Special handling for private/internal IPs
    if (artifactType === 'ip' && isPrivateIP(artifactValue)) {
        return {
            source: 'Network Analysis',
            verdict: 'internal',
            details: `${artifactValue} is a private/internal IP address (RFC 1918). This is an internal network address and cannot be looked up in external threat intelligence. Investigate internal logs for activity from this host.`
        };
    }

    const maliciousResults = {
        ip: {
            source: 'AbuseIPDB',
            verdict: 'malicious',
            details: `IP ${artifactValue} reported ${Math.floor(Math.random() * 500) + 100} times for malicious activity. Abuse confidence score: ${Math.floor(Math.random() * 30) + 70}%.`
        },
        domain: {
            source: 'VirusTotal',
            verdict: 'malicious',
            details: `${Math.floor(Math.random() * 30) + 40}/94 security vendors flagged this domain as malicious.`
        },
        hash: {
            source: 'VirusTotal',
            verdict: 'malicious',
            details: `${Math.floor(Math.random() * 30) + 45}/72 security vendors identified this file as malware.`
        },
        email: {
            source: 'Email Reputation',
            verdict: 'malicious',
            details: `Sender domain is ${Math.floor(Math.random() * 5) + 1} days old and associated with phishing campaigns.`
        },
        url: {
            source: 'URLScan.io',
            verdict: 'malicious',
            details: 'URL hosts credential harvesting page mimicking legitimate login portal.'
        },
        username: {
            source: 'Active Directory',
            verdict: 'suspicious',
            details: `Account shows ${context.failedAttempts || 'multiple'} failed login attempts followed by successful authentication.`
        },
        filename: {
            source: 'Hybrid Analysis',
            verdict: 'malicious',
            details: 'File exhibits behavior consistent with malware: persistence mechanisms, network callbacks, code injection.'
        },
        geolocation: {
            source: 'GeoIP Lookup',
            verdict: 'suspicious',
            details: `Login from ${artifactValue} - unusual location for this user's typical access pattern.`
        },
        port: {
            source: 'Network Analysis',
            verdict: 'suspicious',
            details: `Non-standard port ${artifactValue} commonly used by malware for C2 communication.`
        },
        sql_payload: {
            source: 'WAF Analysis',
            verdict: 'malicious',
            details: `SQL injection payload detected: "${artifactValue}". This pattern attempts to bypass authentication or extract data from the database.`
        },
        target_domain: {
            source: 'Asset Inventory',
            verdict: 'target',
            details: `${artifactValue} is the target application domain. This is the victim site being attacked, not the attacker's infrastructure.`
        }
    };

    const cleanResults = {
        ip: {
            source: 'AbuseIPDB',
            verdict: 'clean',
            details: `IP ${artifactValue} has 0% abuse confidence score. Located in corporate network range.`
        },
        domain: {
            source: 'VirusTotal',
            verdict: 'clean',
            details: '0/94 security vendors flagged this domain. Registered for 5+ years.'
        },
        hash: {
            source: 'VirusTotal',
            verdict: 'clean',
            details: '0/72 security vendors flagged this file. Digitally signed by trusted publisher.'
        },
        email: {
            source: 'Email Reputation',
            verdict: 'clean',
            details: 'Sender has good reputation. Domain is well-established with proper SPF/DKIM.'
        },
        url: {
            source: 'URLScan.io',
            verdict: 'clean',
            details: 'URL belongs to legitimate service with valid SSL certificate.'
        },
        username: {
            source: 'Active Directory',
            verdict: 'clean',
            details: 'User accessed from known location during normal business hours. Activity consistent with role.'
        },
        filename: {
            source: 'Hybrid Analysis',
            verdict: 'clean',
            details: 'File is legitimate system/application binary. Digitally signed.'
        },
        geolocation: {
            source: 'GeoIP Lookup',
            verdict: 'clean',
            details: `Location ${artifactValue} matches user's typical access pattern and travel history.`
        },
        port: {
            source: 'Network Analysis',
            verdict: 'clean',
            details: `Standard port ${artifactValue} used for legitimate application traffic.`
        }
    };

    const result = isMalicious ? maliciousResults[artifactType] : cleanResults[artifactType];

    // Fallback for unknown types
    if (!result) {
        return {
            source: 'Threat Intelligence',
            verdict: isMalicious ? 'suspicious' : 'clean',
            details: isMalicious ? 'Indicator found in threat intelligence feeds.' : 'No matches in threat intelligence feeds.'
        };
    }

    return result;
};

/**
 * Main playbook generator - ROBUST VERSION
 * Parses raw log to extract actual indicators and generates consistent playbook
 */
const generatePlaybook = (alertType, severity, title = '', rawLog = null, details = '') => {
    // Extract real indicators from raw log
    const indicators = extractIndicatorsFromRawLog(rawLog);

    // Analyze if this is malicious based on all available context
    const analysis = analyzeIndicators(indicators, alertType, severity, title);

    // Initialize v2 playbook structure
    let playbook = {
        playbook_version: 2,
        artifacts: [],
        expected_actions: [],
        expected_verdict: analysis.isMalicious ? 'true_positive' : 'false_positive',
        expected_category: analysis.category,
        analysis_notes: analysis.reasons.join('; ')
    };

    let artifactId = 1;

    // Add IP artifacts (mark first as critical)
    indicators.ips.forEach((ip, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'ip',
            value: ip.value,
            is_critical: index === 0, // First IP is critical
            osint_result: generateOSINTResult('ip', ip.value, analysis.isMalicious, { failedAttempts: indicators.failedAttempts })
        });
    });

    // Add username artifacts (critical for auth-related alerts)
    const isAuthRelated = (alertType + title).toLowerCase().match(/login|auth|credential|password|brute/);
    indicators.usernames.forEach((username, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'username',
            value: username.value,
            is_critical: isAuthRelated && index === 0,
            osint_result: generateOSINTResult('username', username.value, analysis.isMalicious, { failedAttempts: indicators.failedAttempts })
        });
    });

    // Add location artifacts
    indicators.locations.forEach((location, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'geolocation',
            value: location.value,
            is_critical: false,
            osint_result: generateOSINTResult('geolocation', location.value, analysis.isMalicious)
        });
    });

    // Add email artifacts (critical for phishing)
    const isPhishing = (alertType + title).toLowerCase().match(/phishing|email|spam/);
    indicators.emails.forEach((email, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'email',
            value: email.value,
            is_critical: isPhishing && index === 0,
            osint_result: generateOSINTResult('email', email.value, analysis.isMalicious)
        });
    });

    // Add domain artifacts
    indicators.domains.forEach((domain, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'domain',
            value: domain.value,
            is_critical: index === 0,
            osint_result: generateOSINTResult('domain', domain.value, analysis.isMalicious)
        });
    });

    // Add URL artifacts
    indicators.urls.forEach((url, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'url',
            value: url.value,
            is_critical: false,
            osint_result: generateOSINTResult('url', url.value, analysis.isMalicious)
        });
    });

    // Add hash artifacts (critical for malware)
    const isMalwareRelated = (alertType + title).toLowerCase().match(/malware|virus|trojan|ransomware/);
    indicators.hashes.forEach((hash, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'hash',
            value: hash.value,
            is_critical: isMalwareRelated && index === 0,
            osint_result: generateOSINTResult('hash', hash.value, analysis.isMalicious)
        });
    });

    // Add filename artifacts
    indicators.filenames.forEach((filename, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'filename',
            value: filename.value,
            is_critical: isMalwareRelated && index === 0,
            osint_result: generateOSINTResult('filename', filename.value, analysis.isMalicious)
        });
    });

    // Add port artifacts
    indicators.ports.forEach((port, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'port',
            value: port.value,
            is_critical: false,
            osint_result: generateOSINTResult('port', port.value, analysis.isMalicious)
        });
    });

    // Add SQL payload artifacts (critical for web attacks)
    const isWebAttack = analysis.category === 'web_attack' || (alertType + title).toLowerCase().match(/sql.*inject|xss|web.*attack/);
    indicators.sqlPayloads.forEach((payload, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'sql_payload',
            value: payload.value,
            is_critical: isWebAttack && index === 0,
            osint_result: generateOSINTResult('sql_payload', payload.value, true) // SQL payloads are always malicious
        });
    });

    // Add target domain artifacts (for context, marked as targets not attackers)
    indicators.targetDomains.forEach((domain, index) => {
        playbook.artifacts.push({
            id: `artifact_${artifactId++}`,
            type: 'target_domain',
            value: domain.value,
            is_critical: false,
            osint_result: generateOSINTResult('target_domain', domain.value, false) // Targets are not malicious
        });
    });

    // If no artifacts extracted, generate based on alert type (fallback)
    if (playbook.artifacts.length === 0) {
        playbook = generateFallbackPlaybook(alertType, severity, title, analysis.isMalicious);
    }

    // Set expected actions based on verdict and category
    if (analysis.isMalicious) {
        switch (analysis.category) {
            case 'credential_attack':
                playbook.expected_actions = ['block_ip', 'reset_credentials'];
                if (severity === 'Critical' || severity === 'High') {
                    playbook.expected_actions.push('isolate_host');
                }
                break;
            case 'malware':
                playbook.expected_actions = ['isolate_host', 'block_hash', 'collect_forensics'];
                break;
            case 'phishing':
                playbook.expected_actions = ['block_sender', 'reset_credentials'];
                break;
            case 'web_attack':
                playbook.expected_actions = ['block_ip', 'escalate'];
                break;
            case 'data_exfiltration':
                playbook.expected_actions = ['isolate_host', 'block_ip', 'collect_forensics', 'escalate'];
                break;
            case 'lateral_movement':
                playbook.expected_actions = ['isolate_host', 'reset_credentials', 'collect_forensics'];
                break;
            default:
                playbook.expected_actions = ['isolate_host', 'collect_forensics'];
        }
    } else {
        playbook.expected_actions = ['close_alert'];
    }

    return playbook;
};

/**
 * Fallback playbook when no indicators can be extracted
 */
const generateFallbackPlaybook = (alertType, severity, title, isMalicious) => {
    const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
    const randomIP = () => `${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`;

    const contextString = (alertType + ' ' + title).toLowerCase();

    let playbook = {
        playbook_version: 2,
        artifacts: [],
        expected_actions: isMalicious ? ['isolate_host', 'collect_forensics'] : ['close_alert'],
        expected_verdict: isMalicious ? 'true_positive' : 'false_positive',
        expected_category: 'suspicious_activity'
    };

    // Generate generic artifacts based on alert type
    if (contextString.match(/phishing|email/)) {
        playbook.expected_category = 'phishing';
        const domain = `${pick(['secure', 'update', 'login'])}-${pick(['microsoft', 'google', 'amazon'])}${pick(['.xyz', '.tk', '.ru'])}`;
        playbook.artifacts = [
            {
                id: 'artifact_1',
                type: 'email',
                value: `security@${domain}`,
                is_critical: true,
                osint_result: generateOSINTResult('email', `security@${domain}`, isMalicious)
            },
            {
                id: 'artifact_2',
                type: 'domain',
                value: domain,
                is_critical: true,
                osint_result: generateOSINTResult('domain', domain, isMalicious)
            }
        ];
        if (isMalicious) {
            playbook.expected_actions = ['block_sender', 'reset_credentials'];
        }
    } else if (contextString.match(/malware|trojan|virus/)) {
        playbook.expected_category = 'malware';
        const hash = Array.from({ length: 64 }, () => '0123456789abcdef'[Math.floor(Math.random() * 16)]).join('');
        playbook.artifacts = [
            {
                id: 'artifact_1',
                type: 'hash',
                value: hash,
                is_critical: true,
                osint_result: generateOSINTResult('hash', hash, isMalicious)
            },
            {
                id: 'artifact_2',
                type: 'ip',
                value: randomIP(),
                is_critical: true,
                osint_result: generateOSINTResult('ip', randomIP(), isMalicious)
            }
        ];
        if (isMalicious) {
            playbook.expected_actions = ['isolate_host', 'block_hash', 'collect_forensics'];
        }
    } else {
        // Generic suspicious activity
        const ip = randomIP();
        playbook.artifacts = [
            {
                id: 'artifact_1',
                type: 'ip',
                value: ip,
                is_critical: true,
                osint_result: generateOSINTResult('ip', ip, isMalicious)
            },
            {
                id: 'artifact_2',
                type: 'username',
                value: pick(['admin', 'service_account', 'root', 'system']),
                is_critical: true,
                osint_result: generateOSINTResult('username', 'user', isMalicious)
            }
        ];
    }

    return playbook;
};

module.exports = { generatePlaybook, extractIndicatorsFromRawLog, analyzeIndicators };
