"""
ddos.py — DDoS log analysis and bot traffic detection.
"""

import os
import re
from collections import Counter
from datetime import date

from modules.output import warn, info, header, good, bad
from modules.utils import require_file


def ddos(log_file):
    """
    Analyze an Apache access log for today's traffic.
    Reports top URLs (100+ hits), top IPs (100+ hits), top user agents (top 10).
    """
    if not require_file(log_file, 'ddos'):
        return

    today = date.today().strftime('%d/%b/%Y')

    urls = Counter()
    ips = Counter()
    agents = Counter()

    try:
        with open(log_file, 'r', errors='replace') as f:
            for line in f:
                if today not in line:
                    continue

                parts = line.split('"')
                # Apache combined log format:
                # IP - user [date] "METHOD URL PROTO" status size "referer" "agent"
                fields = line.split()
                if fields:
                    ips[fields[0]] += 1

                if len(parts) >= 2:
                    # Request field: "METHOD /url HTTP/x.x"
                    req_parts = parts[1].split()
                    if len(req_parts) >= 2:
                        urls[req_parts[1]] += 1

                if len(parts) >= 6:
                    agent = parts[5].strip()
                    if len(agent) >= 50:
                        agents[agent] += 1

    except PermissionError:
        warn(f"Cannot read log file: {log_file}")
        return

    # Top URLs
    print("Top URLs Requested:")
    top_urls = [(u, c) for u, c in urls.most_common(50) if c > 100]
    if top_urls:
        for url, count in top_urls:
            print(f"  {count:>8}  {url}")
    else:
        info("  No URLs with 100+ hits today.")

    print()

    # Top IPs
    print("Top IP Addresses:")
    top_ips = [(ip, c) for ip, c in ips.most_common(50) if c > 100]
    if top_ips:
        for ip, count in top_ips:
            print(f"  {count:>8}  {ip}")
    else:
        info("  No IPs with 100+ hits today.")

    print()

    # Top User Agents
    print("Top User Agents:")
    top_agents = agents.most_common(10)
    if top_agents:
        for agent, count in top_agents:
            print(f"  {count:>8}  {agent}")
    else:
        info("  No qualifying user agents found.")


def bots():
    """
    Scan today's Apache domlogs for bot traffic.
    Reports hit count per log file.
    """
    domlog_dir = '/usr/local/apache/domlogs'
    if not os.path.isdir(domlog_dir):
        warn(f"Domlog directory not found: {domlog_dir}")
        return

    today = date.today().strftime('%d/%b/%Y')
    print("Checking for bot traffic..")

    results = {}
    try:
        for fname in os.listdir(domlog_dir):
            fpath = os.path.join(domlog_dir, fname)
            if not os.path.isfile(fpath):
                continue
            count = 0
            try:
                with open(fpath, 'r', errors='replace') as f:
                    for line in f:
                        if today in line and 'Bot' in line:
                            count += 1
            except PermissionError:
                continue
            if count:
                results[fpath] = count
    except PermissionError:
        warn(f"Cannot access {domlog_dir}")
        return

    if results:
        header(f"\n{'Count':<8} Log File")
        print("-" * 70)
        for path, count in sorted(results.items(), key=lambda x: x[1], reverse=True):
            print(f"{count:<8} {path}")
    else:
        info(f"No bot traffic found for today ({today}).")
