# ANALYSIS PHASE - Breaking down raw data
def analyze_login_data(log_entries):
    """
    ANALYSIS: Break down log data into understandable parts
    """
    print("=== ANALYSIS PHASE ===")
    print("Breaking down raw log data into components:\n")
    
    analysis_results = {
        'usernames': [],
        'ip_addresses': [],
        'timestamps': [],
        'success_count': 0,
        'failed_count': 0
    }
    
    # Break down each log entry into its components
    for i, entry in enumerate(log_entries, 1):
        print(f"Log Entry {i}: {entry}")
        
        # Split the entry into its parts
        parts = entry.split(' | ')
        timestamp = parts[0]
        username = parts[1]
        ip = parts[2]
        status = parts[3]
        
        # Analyze each component
        analysis_results['timestamps'].append(timestamp)
        analysis_results['usernames'].append(username)
        analysis_results['ip_addresses'].append(ip)
        
        if status == 'SUCCESS':
            analysis_results['success_count'] += 1
        else:
            analysis_results['failed_count'] += 1
            
        print(f"  - Timestamp: {timestamp}")
        print(f"  - Username: {username}")
        print(f"  - IP Address: {ip}")
        print(f"  - Status: {status}\n")
    
    return analysis_results

# Raw log data (this is what we start with)
raw_logs = [
    "2024-01-15 14:30:25 | admin | 192.168.1.100 | FAILED",
    "2024-01-15 14:30:26 | admin | 192.168.1.100 | FAILED", 
    "2024-01-15 14:30:27 | admin | 192.168.1.100 | FAILED",
    "2024-01-15 14:30:28 | admin | 192.168.1.100 | SUCCESS",
    "2024-01-15 14:35:10 | user1 | 192.168.1.150 | SUCCESS",
    "2024-01-15 14:35:11 | admin | 10.0.0.15 | FAILED",
    "2024-01-15 14:35:12 | admin | 10.0.0.15 | FAILED"
]

# Run the analysis
analysis_results = analyze_login_data(raw_logs)

# Show analysis summary
print("ANALYSIS SUMMARY:")
print(f"Total usernames found: {len(set(analysis_results['usernames']))}")
print(f"Unique IP addresses: {len(set(analysis_results['ip_addresses']))}")
print(f"Successful logins: {analysis_results['success_count']}")
print(f"Failed logins: {analysis_results['failed_count']}")

# SYNTHESIS PHASE - Building new insights from analyzed components
def synthesize_threat_intelligence(analysis_data):
    """
    SYNTHESIS: Combine analyzed data to create new insights and conclusions
    """
    print("\n=== SYNTHESIS PHASE ===")
    print("Building new insights from analyzed components:\n")
    
    # Create new insights by combining the analyzed data
    threat_report = {
        'suspicious_ips': {},
        'user_risk_profiles': {},
        'attack_patterns': [],
        'security_recommendations': []
    }
    
    # Synthesize IP threat intelligence
    for ip in set(analysis_data['ip_addresses']):
        ip_count = analysis_data['ip_addresses'].count(ip)
        failed_attempts = sum(1 for i, ip_addr in enumerate(analysis_data['ip_addresses']) 
                            if ip_addr == ip and analysis_data['failed_count'] > analysis_data['success_count'])
        
        if failed_attempts > 2:  # Threshold for brute force detection
            threat_report['suspicious_ips'][ip] = {
                'failed_attempts': failed_attempts,
                'risk_level': 'HIGH',
                'conclusion': f"Potential brute force attack from {ip}"
            }
    
    # Synthesize user risk profiles
    for user in set(analysis_data['usernames']):
        user_logins = [i for i, u in enumerate(analysis_data['usernames']) if u == user]
        user_ips = set(analysis_data['ip_addresses'][i] for i in user_logins)
        
        if len(user_ips) > 1:
            threat_report['user_risk_profiles'][user] = {
                'multiple_ips': list(user_ips),
                'risk_level': 'MEDIUM',
                'conclusion': f"User {user} accessed from multiple IPs - possible account sharing"
            }
    
    # Synthesize attack patterns
    if any(ip_data['risk_level'] == 'HIGH' for ip_data in threat_report['suspicious_ips'].values()):
        threat_report['attack_patterns'].append("Brute force attack detected on admin account")
        threat_report['security_recommendations'].extend([
            "Implement account lockout policy",
            "Enable multi-factor authentication",
            "Block suspicious IP addresses"
        ])
    
    return threat_report

# Run synthesis
threat_report = synthesize_threat_intelligence(analysis_results)

# Display the synthesized threat intelligence
print("SYNTHESIZED THREAT INTELLIGENCE REPORT:")
print("=" * 50)

print("\n1. SUSPICIOUS IP ACTIVITY:")
for ip, details in threat_report['suspicious_ips'].items():
    print(f"   🔴 {details['conclusion']}")
    print(f"      Risk Level: {details['risk_level']}")
    print(f"      Failed Attempts: {details['failed_attempts']}")

print("\n2. USER RISK PROFILES:")
for user, details in threat_report['user_risk_profiles'].items():
    print(f"   🟡 {details['conclusion']}")
    print(f"      IPs Used: {', '.join(details['multiple_ips'])}")

print("\n3. IDENTIFIED ATTACK PATTERNS:")
for pattern in threat_report['attack_patterns']:
    print(f"   ⚠️  {pattern}")

print("\n4. SECURITY RECOMMENDATIONS:")
for i, recommendation in enumerate(threat_report['security_recommendations'], 1):
    print(f"   {i}. {recommendation}")
