"""
misc.py — Miscellaneous utility functions.
"""

import os
import re
import subprocess
from collections import Counter
from datetime import date
from pathlib import Path

from modules.output import warn, info, good, bad, header, magenta
from modules.utils import require_bin, require_file, run, php_eol, date_check, get_dir_owner, term_width


def ggloop(filepath, cmd_template):
    """
    Batch execution: read each line from filepath and run cmd_template,
    substituting %v with each line value.

    Example: ggloop('domains.txt', 'checkssl %v')
    """
    if not require_file(filepath, 'ggloop'):
        return

    with open(filepath, 'r') as f:
        lines = [l.rstrip('\n') for l in f if l.strip()]

    for line in lines:
        cmd_str = cmd_template.replace('%v', line)
        print(f"\n--- {cmd_str} ---")
        rc = subprocess.run(cmd_str, shell=True).returncode
        if rc != 0:
            warn(f"Command exited with code {rc}")


def phpusers():
    """List all cPanel users and their assigned PHP versions."""
    userdatadomains = '/etc/userdatadomains'
    if not require_file(userdatadomains, 'phpusers'):
        return

    rebuild = '/usr/local/cpanel/bin/rebuild_phpconf'

    # Get default PHP version
    default_php = ''
    if os.path.isfile(rebuild):
        out, _, _ = run([rebuild, '--current'])
        lines = out.strip().splitlines()
        if lines:
            m = re.search(r':\s*(\S+)', lines[0])
            if m:
                default_php = m.group(1).strip()

    seen = set()
    results = []

    with open(userdatadomains, 'r', errors='replace') as f:
        for line in f:
            parts = line.split('==')
            if len(parts) < 10:
                continue
            user = parts[3].strip()
            php_ver = parts[9].strip()

            if not php_ver or not user:
                continue

            if php_ver == 'inherit':
                php_ver = f"inherit ({default_php})"

            key = f"{user}|{php_ver}"
            if key not in seen:
                seen.add(key)
                results.append((user, php_ver))

    results.sort()
    user_w = max(25, term_width() // 4)
    header(f"{'cPanel User':<{user_w}} PHP Version")
    print("-" * min(term_width(), user_w + 30))
    for user, php_ver in results:
        print(f"{user:<{user_w}} {php_ver}")


def errors(cwd=None):
    """
    Find all error_log files under current directory and show today's entries.
    Best run from within public_html.
    """
    cwd = cwd or os.getcwd()
    today = date.today().strftime('%d-%b-%Y')

    found_any = False
    for root, dirs, files in os.walk(cwd):
        if 'error_log' in files:
            fpath = os.path.join(root, 'error_log')
            try:
                with open(fpath, 'r', errors='replace') as f:
                    for line in f:
                        if today in line:
                            print(f"{fpath}: {line.rstrip()}")
                            found_any = True
            except PermissionError:
                warn(f"Cannot read {fpath}")

    if not found_any:
        info(f"No error_log entries found for today ({today}).")


def robotstxt():
    """
    Find robots.txt files across /home/ and report crawl-delay directives.
    """
    home = '/home/'
    found = False

    for root, dirs, files in os.walk(home):
        if 'robots.txt' in files:
            fpath = os.path.join(root, 'robots.txt')
            try:
                with open(fpath, 'r', errors='replace') as f:
                    for i, line in enumerate(f, 1):
                        if 'delay' in line.lower() and not line.strip().startswith('#'):
                            print(f"{fpath}:{i}: {line.rstrip()}")
                            found = True
            except PermissionError:
                continue

    if not found:
        info("No crawl-delay directives found in any robots.txt.")


def docroot_lookup(domain):
    """Alias for dns.docroot — here for ggloop compatibility."""
    from modules.dns import docroot
    docroot(domain)


def getea4php():
    """List EA4 PHP versions with EOL status."""
    rebuild = '/usr/local/cpanel/bin/rebuild_phpconf'
    if not os.path.isfile(rebuild):
        warn("rebuild_phpconf not found.")
        return

    out, _, _ = run([rebuild, '--current'])
    lines = out.strip().splitlines()

    for i, line in enumerate(lines):
        line = line.strip()
        if i == 0:
            print(f"  {line}")
            continue
        m = re.search(r'ea-php(\d+)', line)
        if m:
            raw = m.group(1)
            ver = f"{raw[0]}.{raw[1]}"
            eol = php_eol(ver)
            colored = date_check(eol)
            print(f"  {line}  {colored}")
        else:
            print(f"  {line}")


def listfunctions():
    """Print the full color-coded help menu."""
    from modules.output import COLORAMA_AVAILABLE
    if COLORAMA_AVAILABLE:
        from colorama import Fore, Back, Style
        C = Fore.CYAN
        M = Fore.MAGENTA
        R = Style.RESET_ALL
        WARN = Back.RED + Fore.WHITE
        OK = Back.GREEN + Fore.BLACK
    else:
        C = M = R = WARN = OK = ''

    def cmd(name, desc):
        print(f"  {C}{name:<22}{R} — {desc}")

    def cmd_warn(name, desc):
        print(f"  {WARN}{name:<22}{R} — {desc}")

    def cmd_ok(name, desc):
        print(f"  {OK}{name:<22}{R} — {desc}")

    print()
    print("  === GGVPS Troubleautomagic — Available Commands ===")
    print()
    print("  [Apache]")
    cmd("apacheprocs", "List all current Apache processes (IP, method, host, URL).")
    cmd("apache-stats", "Summarize Apache workers per domain. Useful for MaxRequestWorkers issues.")
    print()
    print("  [Disk]")
    cmd("tops", "Top N largest files/dirs. Usage: tops [N] [-d <dir>]")
    cmd("finddiskspace", "Report disk usage; list large files if over 25%.")
    cmd("dspace", "Deep disk scan: directories and files over 200MB in /home and /backup.")
    cmd("findbigdirs", "Find directories with 800+ files in public_html / mail.")
    print()
    print("  [Email]")
    cmd("spamcheck", "Full email health report: queue, relays, Dovecot logins, eximstats.")
    cmd("lsforwards", "List all active email forwarders.")
    cmd("exim-security", "Show Exim TLS options and cipher suite.")
    print()
    print("  [Security]")
    cmd_warn("enable-root", "[WARNING] Enable root SSH password auth. Advise client first.")
    cmd_warn("disable-root", "Disable root SSH password auth.")
    cmd("pass-security", "Verify mailbox password against shadow hash. Usage: pass-security email pass")
    cmd_warn("sec-disable", "[WARNING] Disable cPanel Security Questions. Re-enable when done.")
    cmd("sec-enable", "Re-enable cPanel Security Questions.")
    cmd("hack", "Scan domlogs for wp-login/xmlrpc/admin-ajax brute force.")
    cmd("blocks", "Show today's CSF/LFD blocked IPs.")
    cmd("wpsecurity", "Find Wordfence and WP-Cerber installations.")
    print()
    print("  [DNS & Domains]")
    cmd("zone", "Show BIND zone file for a domain. Usage: zone domain.tld")
    cmd("checkssl", "Check SSL cert (SANs, issuer, expiry). Usage: checkssl domain.tld")
    cmd("docroot", "Get document root for a domain. Usage: docroot domain.tld")
    cmd("lsdomains", "List all domains and their cPanel owners.")
    print()
    print("  [DDoS & Bots]")
    cmd("ddos", "Analyze an access log for today's DDoS patterns. Usage: ddos <logfile>")
    cmd("bots", "Scan domlogs for today's bot traffic.")
    print()
    print("  [WordPress]")
    cmd("wpfunctions", "Show WordPress function help menu.")
    cmd("wpaudit", "WP install summary (url, version, plugin/theme counts). Run from WP dir.")
    cmd("wppluginlist", "List WP plugins as directory owner. Run from WP dir.")
    cmd("wpthemelist", "List WP themes as directory owner. Run from WP dir.")
    cmd("wpoldplugins", "Check all WP plugins: version, last updated, flag old/outdated.")
    cmd("wpcreateadmin", "Create a temporary admin user (auto-deleted in 30 min). Run from WP dir.")
    print()
    print("  [Network]")
    cmd("cfallow", "Whitelist all Cloudflare IPv4 ranges in CSF.")
    cmd("masscf", "Apply any CSF action to all Cloudflare IPs. Usage: masscf <flag>")
    cmd("ggnull", "Null-route an IP. Usage: ggnull <ip>")
    cmd("ggpaste", "Upload to GreenGeeks paste service. Usage: ggpaste <type> [file]")
    cmd("fix-license", "Run cpkeyclt to fix cPanel license.")
    cmd("summary", "Run the GreenGeeks server migration summary script.")
    print()
    print("  [Misc]")
    cmd("ggloop", "Batch run a command from a file. Usage: ggloop <file> <cmd %v>")
    cmd("phpusers", "List cPanel users and their PHP versions.")
    cmd("errors", "Find today's error_log entries in current directory.")
    cmd("robotstxt", "Find crawl-delay directives in robots.txt files.")
    cmd_ok("help / ?", "Show this menu.")
    print()
