from collections import defaultdict

from pcapx.core.detections.dns_behavior import detect_dns_behavior
from pcapx.core.detections.recon_behavior import detect_recon_behavior
from pcapx.core.detections.c2_behavior import detect_periodic_connections
from pcapx.core.detections.exploit_patterns import detect_exploit_patterns


def _normalize_pair(a, b):
    """Ensure bidirectional traffic collapses into one finding"""
    return tuple(sorted([a, b]))


def generate_findings(result: dict):
    findings = {}
    index = result["index"]
    auth = result.get("auth", {})

    # ================= AUTH: CLEARTEXT =================
    creds = auth.get("credentials", [])
    if creds:
        src = creds[0]["src"]
        dst = creds[0]["dst"]

        key = f"AUTH_CLEARTEXT:FTP:{src}:{dst}"
        findings[key] = {
            "id": key,
            "title": "Cleartext Credentials Observed (FTP)",
            "severity": "HIGH",
            "what_happened": (
                "FTP authentication credentials were transmitted in cleartext "
                "during multiple authentication attempts."
            ),
            "why_it_matters": (
                "Cleartext authentication allows any network observer to capture "
                "credentials and reuse them for unauthorized access or lateral movement."
            ),
            "evidence": {
                "credential_events": len(creds),
            },
            "affected_assets": [
                f"Client: {src}",
                f"Server: {dst}",
            ],
        }

    # ================= DNS BEHAVIOR =================
    for d in detect_dns_behavior(index.get("dns", [])):
        key = f"DNS_BEHAVIOR:ANOMALOUS:{d['domain']}"
        findings[key] = {
            "id": key,
            "title": "Unusual DNS Query Structure Observed",
            "severity": "LOW",
            "what_happened": (
                "DNS queries contained unusually long or structured labels."
            ),
            "why_it_matters": (
                "Such patterns are commonly associated with automated or non-human "
                "generated traffic."
            ),
            "evidence": d,
            "affected_assets": [d["domain"]],
        }

    # ================= RECON =================
    for r in detect_recon_behavior(index.get("connections", [])):
        key = f"RECON_BEHAVIOR:PORT_ACTIVITY:{r['src']}"
        findings[key] = {
            "id": key,
            "title": "Broad Port Interaction Observed",
            "severity": "LOW",
            "what_happened": (
                f"{r['port_count']} unique destination ports were contacted by the same source."
            ),
            "why_it_matters": (
                "This behavior may indicate automated service discovery, "
                "inventory scanning, or a misconfigured application."
            ),
            "evidence": r,
            "affected_assets": [r["src"]],
        }

    # ================= PERIODIC COMMUNICATION (DEDUPED) =================
    periodic = defaultdict(lambda: {"count": 0})

    for p in detect_periodic_connections(index.get("connections", [])):
        a, b = _normalize_pair(p["src"], p["dst"])
        periodic[(a, b)]["count"] += p["count"]

    for (a, b), meta in periodic.items():
        key = f"NET_BEHAVIOR:PERIODIC:{a}:{b}"
        findings[key] = {
            "id": key,
            "title": "Regular Communication Pattern Observed",
            "severity": "LOW",
            "what_happened": (
                f"Repeated bidirectional communication was observed "
                f"between the same hosts ({meta['count']} connections)."
            ),
            "why_it_matters": (
                "Regular communication patterns are commonly associated with "
                "automated clients, background services, or persistent applications."
            ),
            "evidence": {
                "direction": "bidirectional",
                "connections": meta["count"],
            },
            "affected_assets": [a, b],
        }

    # ================= EXPLOIT-LIKE PAYLOADS (LOW CONFIDENCE) =================
    for e in detect_exploit_patterns(index.get("http", [])):
        key = "APP_BEHAVIOR:SUSPICIOUS_PAYLOAD"

        findings[key] = {
            "id": key,
            "title": "Suspicious Application Payload Observed",
            "severity": "LOW",
            "what_happened": (
                "Application-layer requests contained patterns loosely associated "
                "with known exploitation techniques."
            ),
            "why_it_matters": (
                "While not conclusive on its own, such payloads may indicate "
                "probing or misuse of an application endpoint and warrant review."
            ),
            "evidence": e,
            "affected_assets": e.get("assets", ["unknown"]),
        }

    return list(findings.values())
