import json
import time
from datetime import datetime
from kafka import KafkaProducer
import psycopg2

producer = KafkaProducer(
    bootstrap_servers=['10.0.0.15:9093'],
    value_serializer=lambda x: json.dumps(x).encode('utf-8')
)

known_attack_ip = "203.0.113.99"

# ── سجل حقيقي 100% من ملف 02-21-2018.csv (DDOS attack-HOIC) ──
attack_record = {
    "timestamp": datetime.now().isoformat(),
    "src_ip": known_attack_ip,
    "Dst Port": 880.0,
    "Protocol": 6.0,
    "Flow Duration": 1.0,
    "Tot Fwd Pkts": 3.0,
    "Tot Bwd Pkts": 4.0,
    "TotLen Fwd Pkts": 316.0,
    "TotLen Bwd Pkts": 935.0,
    "Fwd Pkt Len Max": 316.0,
    "Fwd Pkt Len Min": 0.0,
    "Bwd Pkt Len Max": 935.0,
    "Bwd Pkt Len Min": 0.0,
    "Flow Pkts/s": 6.1001487,
    "Flow Byts/s": 15.6123,
    "Fwd Header Len": 7.0,
    "Bwd Header Len": 9.0,
    "Fwd Pkts/s": 97.4714923,
    "Bwd Pkts/s": 36.6286564,
    "Pkt Len Min": 8.0,
    "Pkt Len Max": 95.0,
    "SYN Flag Cnt": 7.0,
    "RST Flag Cnt": 3.0,
    "PSH Flag Cnt": 2.0,
    "ACK Flag Cnt": 1.0,
    "label": "DDOS attack-HOIC"
}

print(f"[T=0] Sending REAL DDOS attack-HOIC record (src_ip={known_attack_ip}) to Kafka...")
attack_start_time = time.time()
producer.send('network-logs', value=attack_record)
producer.flush()
print(f"Sent at: {attack_record['timestamp']}")

conn = psycopg2.connect(
    host="10.0.0.18", dbname="ids_db",
    user="ids_user", password="ids_pass123"
)
cur = conn.cursor()

print("Monitoring PostgreSQL for detection (polling every 0.5s)...")
timeout_seconds = 60
detected = False

while (time.time() - attack_start_time) < timeout_seconds:
    cur.execute("""
        SELECT id, attack_type, occurrence_count, created_at FROM alerts
        WHERE src_ip = %s ORDER BY created_at DESC LIMIT 1
    """, (known_attack_ip,))
    result = cur.fetchone()
    if result:
        detection_latency = time.time() - attack_start_time
        print(f"\nDETECTED")
        print(f"Attack type: {result[1]}")
        print(f"Detection latency: {detection_latency:.2f} seconds")
        detected = True
        break
    time.sleep(0.5)

if not detected:
    print(f"\nNo detection within {timeout_seconds}s timeout")

cur.close()
conn.close()
