#!/usr/bin/env python3
"""
Cold Email Infrastructure Health Checker

Checks SPF, DKIM, and DMARC DNS records for a sending domain.
Outputs a pass/fail/warning report with plain-English fix instructions.

Usage:
    python check_email_infra.py yourdomain.com
    python check_email_infra.py domain1.com domain2.com
    python check_email_infra.py yourdomain.com --dkim-selector s1
    python check_email_infra.py yourdomain.com --json
    python check_email_infra.py yourdomain.com --quiet

Exit codes:
    0 = all checks pass
    1 = warnings only (no failures)
    2 = one or more failures
"""

import argparse
import json
import sys
from datetime import datetime, timezone

try:
    import dns.resolver
    import dns.exception
except ImportError:
    print("Error: dnspython is not installed.")
    print("Run: pip install dnspython")
    sys.exit(2)


# ── Constants ─────────────────────────────────────────────────────────────────

VERSION = "1.0.0"

COMMON_DKIM_SELECTORS = [
    "google", "mail", "k1", "s1", "s2",
    "selector1", "selector2", "default",
    "dkim", "email", "mandrill", "mailjet",
    "smtp", "postmaster", "mx",
]

SPF_LOOKUP_MECHANISMS = {"include", "a", "mx", "ptr", "exists"}

STATUS_PASS    = "PASS"
STATUS_WARN    = "WARN"
STATUS_FAIL    = "FAIL"
STATUS_SKIP    = "SKIP"

ICON = {
    STATUS_PASS: "✅",
    STATUS_WARN: "⚠️ ",
    STATUS_FAIL: "❌",
    STATUS_SKIP: "⏭️ ",
}

GRADE_ORDER = {STATUS_FAIL: 0, STATUS_WARN: 1, STATUS_PASS: 2, STATUS_SKIP: 3}


# ── DNS helpers ───────────────────────────────────────────────────────────────

def resolve_txt(name: str) -> list[str]:
    """Return a list of TXT record strings for *name*, or [] on any error."""
    try:
        answers = dns.resolver.resolve(name, "TXT", lifetime=8)
        results = []
        for rdata in answers:
            # Each rdata may be split across multiple strings — join them
            record = "".join(s.decode("utf-8", errors="replace") for s in rdata.strings)
            results.append(record)
        return results
    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
        return []
    except dns.exception.DNSException:
        return []


# ── SPF check ─────────────────────────────────────────────────────────────────

def check_spf(domain: str) -> dict:
    """
    Check SPF record at the root domain.

    Returns:
        {status, record, summary, fix, lookup_count, all_qualifier}
    """
    records = resolve_txt(domain)
    spf_records = [r for r in records if r.lower().startswith("v=spf1")]

    if not spf_records:
        return {
            "status": STATUS_FAIL,
            "record": None,
            "summary": "No SPF record found",
            "fix": (
                f"Add a TXT record to your DNS:\n"
                f"  Name:  {domain}\n"
                f"  Value: v=spf1 include:_spf.google.com ~all\n\n"
                f"Replace `include:_spf.google.com` with your email provider's include.\n"
                f"Common providers:\n"
                f"  Google Workspace:  include:_spf.google.com\n"
                f"  Microsoft 365:     include:spf.protection.outlook.com\n"
                f"  SendGrid:          include:sendgrid.net\n"
                f"  Mailchimp:         include:servers.mcsv.net\n\n"
                f"Allow up to 48 hours for DNS propagation."
            ),
        }

    if len(spf_records) > 1:
        return {
            "status": STATUS_FAIL,
            "record": spf_records[0],
            "summary": f"Multiple SPF records found ({len(spf_records)}) — only one is allowed",
            "fix": (
                "Remove all but one SPF TXT record from your DNS.\n"
                "Having more than one SPF record causes immediate authentication failure.\n"
                "If you send from multiple services, combine them into a single record:\n"
                f"  v=spf1 include:_spf.google.com include:sendgrid.net ~all"
            ),
        }

    record = spf_records[0]
    parts = record.split()

    # Count DNS-lookup mechanisms (RFC 7208 limit: 10)
    lookup_count = sum(
        1 for p in parts
        if any(p.lower().startswith(m + ":") or p.lower() == m for m in SPF_LOOKUP_MECHANISMS)
    )

    # Find the `all` qualifier
    all_qualifier = None
    for part in parts:
        p = part.lower()
        if p in ("+all", "-all", "~all", "?all", "all"):
            all_qualifier = p
            break

    # Evaluate
    if all_qualifier == "+all":
        return {
            "status": STATUS_WARN,
            "record": record,
            "summary": "+all detected — any server can send as your domain",
            "lookup_count": lookup_count,
            "all_qualifier": all_qualifier,
            "fix": (
                f"Your SPF record ends with `+all`, which authorises any mail server in the world\n"
                f"to send email on behalf of {domain}. This is equivalent to having no SPF at all.\n\n"
                f"Change `+all` to `~all` (softfail) or `-all` (hardfail):\n"
                f"  ~all  Unauthorised mail is marked suspicious (recommended)\n"
                f"  -all  Unauthorised mail is rejected outright\n\n"
                f"Start with ~all. Move to -all once you're confident all legitimate\n"
                f"sending sources are included in the record."
            ),
        }

    if all_qualifier == "?all":
        return {
            "status": STATUS_WARN,
            "record": record,
            "summary": "?all detected — neutral policy provides no spam protection",
            "lookup_count": lookup_count,
            "all_qualifier": all_qualifier,
            "fix": (
                f"Your SPF record ends with `?all` (neutral). This tells receiving servers to\n"
                f"take no action on unauthorised mail — effectively no protection.\n\n"
                f"Change `?all` to `~all` or `-all` for meaningful enforcement."
            ),
        }

    if lookup_count > 9:
        return {
            "status": STATUS_FAIL,
            "record": record,
            "summary": f"SPF lookup count is {lookup_count} (RFC limit: 10) — authentication will fail",
            "lookup_count": lookup_count,
            "all_qualifier": all_qualifier,
            "fix": (
                f"Your SPF record requires {lookup_count} DNS lookups. The RFC 7208 limit is 10.\n"
                f"Mail servers that strictly enforce this will fail authentication.\n\n"
                f"To reduce lookups:\n"
                f"  1. Remove any sending services you no longer use\n"
                f"  2. Use a SPF flattening service (e.g. dmarcly.com/tools/spf-flattener)\n"
                f"     to replace nested includes with direct IP ranges"
            ),
        }

    if lookup_count > 7:
        status = STATUS_WARN
        summary = f"SPF lookup count is {lookup_count}/10 — approaching the RFC limit"
        fix = (
            f"You currently use {lookup_count} of the 10 allowed SPF DNS lookups.\n"
            f"If you add another sending service, you may exceed the limit.\n\n"
            f"Consider removing unused service includes or using SPF flattening."
        )
    elif all_qualifier is None:
        status = STATUS_WARN
        summary = "SPF record has no `all` mechanism — policy is incomplete"
        fix = (
            f"Add `~all` or `-all` to the end of your SPF record:\n"
            f"  Current: {record}\n"
            f"  Fixed:   {record} ~all"
        )
    else:
        status = STATUS_PASS
        summary = f"Valid SPF record · {lookup_count} DNS lookups · ends with {all_qualifier}"
        fix = None

    return {
        "status": status,
        "record": record,
        "summary": summary,
        "lookup_count": lookup_count,
        "all_qualifier": all_qualifier,
        "fix": fix,
    }


# ── DKIM check ────────────────────────────────────────────────────────────────

def check_dkim(domain: str, custom_selector: str | None = None) -> dict:
    """
    Check DKIM record. Tries common selectors, or a user-supplied one.

    Returns:
        {status, selector, record, summary, fix, key_length_estimate}
    """
    selectors_to_try = [custom_selector] if custom_selector else COMMON_DKIM_SELECTORS

    for selector in selectors_to_try:
        name = f"{selector}._domainkey.{domain}"
        records = resolve_txt(name)
        dkim_records = [r for r in records if "v=DKIM1" in r or "p=" in r]

        if not dkim_records:
            continue

        record = dkim_records[0]

        # Extract the public key from p=
        key_b64 = ""
        for tag in record.replace("; ", ";").split(";"):
            tag = tag.strip()
            if tag.lower().startswith("p="):
                key_b64 = tag[2:].strip()
                break

        if not key_b64:
            return {
                "status": STATUS_FAIL,
                "selector": selector,
                "record": record,
                "summary": f"DKIM record found at selector '{selector}' but public key (p=) is empty",
                "fix": (
                    f"Your DKIM record at {selector}._domainkey.{domain} has an empty p= tag.\n"
                    f"This usually means DKIM signing has been disabled.\n\n"
                    f"Re-enable DKIM in your email sending service and update the DNS record\n"
                    f"with the new public key it generates."
                ),
            }

        # Estimate key length from base64 string length (without header overhead)
        # 2048-bit RSA DER ≈ 294 bytes ≈ 392 b64 chars
        # 1024-bit RSA DER ≈ 148 bytes ≈ 200 b64 chars
        key_len_estimate = None
        b64_len = len(key_b64.replace(" ", "").replace("\n", ""))
        if b64_len > 320:
            key_len_estimate = 2048
        elif b64_len > 150:
            key_len_estimate = 1024
        else:
            key_len_estimate = 512

        if key_len_estimate is not None and key_len_estimate < 1024:
            return {
                "status": STATUS_WARN,
                "selector": selector,
                "record": record,
                "summary": f"Selector '{selector}' found — estimated key length {key_len_estimate} bits (1024+ recommended)",
                "key_length_estimate": key_len_estimate,
                "fix": (
                    f"Your DKIM key appears to be shorter than 1024 bits, which is considered\n"
                    f"weak by current standards. Gmail recommends 2048 bits.\n\n"
                    f"To fix: regenerate your DKIM key in your email sending service:\n"
                    f"  Google Workspace: Admin > Apps > Gmail > Authenticate email\n"
                    f"  Microsoft 365:    Admin > Settings > Domains > {domain} > DKIM\n\n"
                    f"Update the DNS record at {selector}._domainkey.{domain} with the new key."
                ),
            }

        if key_len_estimate == 1024:
            return {
                "status": STATUS_WARN,
                "selector": selector,
                "record": record,
                "summary": f"Selector '{selector}' found — estimated key length 1024 bits (2048 recommended)",
                "key_length_estimate": key_len_estimate,
                "fix": (
                    f"Your DKIM key is estimated at 1024 bits. Gmail and Microsoft recommend 2048 bits.\n"
                    f"1024-bit keys are still accepted but flagged in some spam analysis tools.\n\n"
                    f"To upgrade: regenerate your DKIM key in your email sending service and\n"
                    f"update the DNS record at {selector}._domainkey.{domain} with the new key.\n"
                    f"Allow 48 hours for DNS propagation after updating."
                ),
            }

        return {
            "status": STATUS_PASS,
            "selector": selector,
            "record": record,
            "summary": f"Selector '{selector}' found — valid DKIM record",
            "key_length_estimate": key_len_estimate,
            "fix": None,
        }

    # No selector matched
    selector_note = (
        f"  Your sending service may use a custom selector.\n"
        f"  Pass it with: python check_email_infra.py {domain} --dkim-selector YOUR_SELECTOR\n\n"
        f"  To find your selector: check your email sending service dashboard,\n"
        f"  or look at the DKIM-Signature header in an email you've sent\n"
        f"  (in Gmail: open email > three dots > Show original > find DKIM-Signature: s=XXX)."
    )

    return {
        "status": STATUS_FAIL,
        "selector": None,
        "record": None,
        "summary": (
            f"No DKIM record found at any of {len(selectors_to_try)} common selectors"
            if not custom_selector
            else f"No DKIM record found at selector '{custom_selector}'"
        ),
        "fix": (
            f"No DKIM record was found for {domain}.\n\n"
            f"How to set up DKIM:\n"
            f"  Google Workspace: Admin > Apps > Gmail > Authenticate email > Generate new record\n"
            f"  Microsoft 365:    Admin > Settings > Domains > {domain} > DKIM tab\n"
            f"  SendGrid:         Settings > Sender Authentication > Domain Authentication\n\n"
            + (selector_note if not custom_selector else "")
        ),
    }


# ── DMARC check ───────────────────────────────────────────────────────────────

def check_dmarc(domain: str) -> dict:
    """
    Check DMARC record at _dmarc.{domain}.

    Returns:
        {status, record, policy, summary, fix}
    """
    name = f"_dmarc.{domain}"
    records = resolve_txt(name)
    dmarc_records = [r for r in records if r.lower().startswith("v=dmarc1")]

    if not dmarc_records:
        return {
            "status": STATUS_FAIL,
            "record": None,
            "policy": None,
            "summary": f"No DMARC record found at {name}",
            "fix": (
                f"Add a TXT record to your DNS:\n"
                f"  Name:  _dmarc.{domain}\n"
                f"  Value: v=DMARC1; p=quarantine; rua=mailto:dmarc@{domain}\n\n"
                f"Policy options:\n"
                f"  p=none        Monitor only — no enforcement (useful for initial rollout)\n"
                f"  p=quarantine  Send failing mail to spam (recommended)\n"
                f"  p=reject      Reject failing mail outright (strictest)\n\n"
                f"Start with p=quarantine. Move to p=reject once you've confirmed all\n"
                f"legitimate mail is passing. The rua= tag sends aggregate reports to\n"
                f"the specified email so you can monitor authentication results.\n\n"
                f"Allow up to 48 hours for DNS propagation."
            ),
        }

    record = dmarc_records[0]

    # Parse p= value
    policy = None
    for tag in record.replace("; ", ";").split(";"):
        tag = tag.strip().lower()
        if tag.startswith("p="):
            policy = tag[2:].strip()
            break

    if policy == "none":
        return {
            "status": STATUS_WARN,
            "record": record,
            "policy": policy,
            "summary": "p=none — monitoring mode only, no enforcement",
            "fix": (
                f"Your DMARC policy is set to p=none. This means receiving servers log\n"
                f"authentication failures but don't act on them — mail still delivers.\n\n"
                f"p=none is a valid starting point for rollout, but it provides no\n"
                f"protection against spoofing or delivery issues.\n\n"
                f"Once you've confirmed your legitimate mail is passing (check your\n"
                f"DMARC aggregate reports), upgrade to p=quarantine:\n"
                f"  Current: {record}\n"
                f"  Updated: v=DMARC1; p=quarantine; rua=mailto:dmarc@{domain}"
            ),
        }

    if policy in ("quarantine", "reject"):
        enforcement_note = (
            "Failing mail is rejected outright." if policy == "reject"
            else "Failing mail is sent to the spam folder."
        )
        return {
            "status": STATUS_PASS,
            "record": record,
            "policy": policy,
            "summary": f"p={policy} — {enforcement_note}",
            "fix": None,
        }

    # Unknown or missing policy
    return {
        "status": STATUS_WARN,
        "record": record,
        "policy": policy,
        "summary": f"DMARC record found but policy is unclear (p={policy or 'missing'})",
        "fix": (
            f"Your DMARC record was found but the p= (policy) tag is {f'set to {policy!r}' if policy else 'missing'}.\n"
            f"Set it to quarantine or reject:\n"
            f"  v=DMARC1; p=quarantine; rua=mailto:dmarc@{domain}"
        ),
    }


# ── Grade ─────────────────────────────────────────────────────────────────────

def calculate_grade(spf: dict, dkim: dict, dmarc: dict) -> str:
    statuses = [spf["status"], dkim["status"], dmarc["status"]]
    failures = sum(1 for s in statuses if s == STATUS_FAIL)
    warnings = sum(1 for s in statuses if s == STATUS_WARN)

    if failures >= 2:
        return "F"
    if failures == 1:
        return "C"
    if warnings:
        return "B"
    return "A"


GRADE_SUMMARY = {
    "A": "All three checks pass. Your sending domain is well-configured.",
    "B": "No failures, but there are warnings worth addressing.",
    "C": "One check failing. Your cold emails are likely landing in spam for some recipients.",
    "F": "Two or more checks failing. Your cold emails are likely being rejected or silently dropped.",
}


# ── Output formatting ─────────────────────────────────────────────────────────

try:
    import shutil
    _TERM_WIDTH = shutil.get_terminal_size().columns
except Exception:
    _TERM_WIDTH = 80

_DIVIDER = "━" * min(60, _TERM_WIDTH)
_THIN    = "─" * min(60, _TERM_WIDTH)


def _c(text: str, code: str) -> str:
    """Wrap text in ANSI colour code."""
    return f"\033[{code}m{text}\033[0m"


def _green(t):  return _c(t, "32")
def _yellow(t): return _c(t, "33")
def _red(t):    return _c(t, "31")
def _bold(t):   return _c(t, "1")
def _dim(t):    return _c(t, "2")


def _colour_for(status: str):
    return {STATUS_PASS: _green, STATUS_WARN: _yellow, STATUS_FAIL: _red}.get(status, lambda x: x)


def print_report(domain: str, spf: dict, dkim: dict, dmarc: dict, quiet: bool = False):
    now = datetime.now(timezone.utc).strftime("%a %d %b %Y · %H:%M UTC")
    grade = calculate_grade(spf, dkim, dmarc)
    issues = [(n, r) for n, r in [("SPF", spf), ("DKIM", dkim), ("DMARC", dmarc)]
              if r["status"] in (STATUS_FAIL, STATUS_WARN)]

    if not quiet:
        print()
        print(_bold(f"Cold Email Infrastructure Health Check — {domain}"))
        print(_dim(f"Checked: {now}"))
        print()

    checks = [("SPF", spf), ("DKIM", dkim), ("DMARC", dmarc)]
    any_printed = False
    for name, result in checks:
        if quiet and result["status"] == STATUS_PASS:
            continue
        icon = ICON[result["status"]]
        colour = _colour_for(result["status"])
        status_label = colour(result["status"].ljust(7))
        print(f"  {icon}  {name:<6}  {status_label}  {result['summary']}")
        any_printed = True

    if quiet and not any_printed:
        print(_green(f"  ✅  {domain} — all checks pass"))
        return

    if not quiet:
        print()
        print(_DIVIDER)

        grade_colour = {
            "A": _green, "B": _yellow, "C": _yellow, "F": _red
        }.get(grade, lambda x: x)

        issue_count = len(issues)
        issue_word = "issue" if issue_count == 1 else "issues"
        print(_bold(f"Grade: {grade_colour(grade)}   ·   {issue_count} {issue_word} found"))
        print()
        print(GRADE_SUMMARY[grade])

    if issues:
        print()
        print(_THIN)
        print(_bold("What to fix"))
        print(_THIN)
        for name, result in issues:
            colour = _colour_for(result["status"])
            label = "Warning" if result["status"] == STATUS_WARN else "Failure"
            print()
            print(_bold(f"{name} — {colour(label)}"))
            print(f"  {result['summary']}")
            if result.get("fix"):
                print()
                for line in result["fix"].split("\n"):
                    print(f"  {line}")

    if not quiet:
        print()
        print(_THIN)
        print(_bold("Grade scale"))
        print(_THIN)
        for g, desc in [("A", "All three pass"), ("B", "Passes with warnings only"),
                        ("C", "One check failing"), ("F", "Two or more checks failing")]:
            c = {
                "A": _green, "B": _yellow, "C": _yellow, "F": _red
            }[g]
            print(f"  {c(g)}: {desc}")

        print()
        print(_THIN)
        print(_bold("Run again after making changes"))
        print(_THIN)
        print("  DNS changes take up to 48 hours to propagate.")
        print(f"  python check_email_infra.py {domain}")
        print()
        print(_dim("Powered by Tincture · tinctu.re/tools/cold-email-checker"))
        print()


def print_json(domain: str, spf: dict, dkim: dict, dmarc: dict):
    grade = calculate_grade(spf, dkim, dmarc)
    output = {
        "domain": domain,
        "checked_at": datetime.now(timezone.utc).isoformat(),
        "grade": grade,
        "checks": {
            "spf": {
                "status": spf["status"],
                "summary": spf["summary"],
                "record": spf.get("record"),
                "fix": spf.get("fix"),
            },
            "dkim": {
                "status": dkim["status"],
                "summary": dkim["summary"],
                "selector": dkim.get("selector"),
                "record": dkim.get("record"),
                "fix": dkim.get("fix"),
            },
            "dmarc": {
                "status": dmarc["status"],
                "summary": dmarc["summary"],
                "policy": dmarc.get("policy"),
                "record": dmarc.get("record"),
                "fix": dmarc.get("fix"),
            },
        },
        "issues": [
            name for name, r in [("spf", spf), ("dkim", dkim), ("dmarc", dmarc)]
            if r["status"] in (STATUS_FAIL, STATUS_WARN)
        ],
    }
    print(json.dumps(output, indent=2))


# ── CLI ───────────────────────────────────────────────────────────────────────

def parse_args():
    parser = argparse.ArgumentParser(
        prog="check_email_infra",
        description="Check SPF, DKIM, and DMARC DNS records for a sending domain.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python check_email_infra.py yourdomain.com
  python check_email_infra.py yourdomain.com --dkim-selector s1
  python check_email_infra.py domain1.com domain2.com domain3.com
  python check_email_infra.py yourdomain.com --json
  python check_email_infra.py yourdomain.com --quiet
        """,
    )
    parser.add_argument("domains", nargs="+", metavar="DOMAIN", help="Domain(s) to check")
    parser.add_argument("--dkim-selector", metavar="SELECTOR", help="DKIM selector to use (overrides auto-detection)")
    parser.add_argument("--json", action="store_true", help="Output results as JSON")
    parser.add_argument("--quiet", "-q", action="store_true", help="Only print warnings and failures")
    parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
    return parser.parse_args()


def run_checks(domain: str, dkim_selector: str | None) -> tuple[dict, dict, dict]:
    domain = domain.lower().strip().rstrip(".")
    spf   = check_spf(domain)
    dkim  = check_dkim(domain, custom_selector=dkim_selector)
    dmarc = check_dmarc(domain)
    return spf, dkim, dmarc


def exit_code_for(spf: dict, dkim: dict, dmarc: dict) -> int:
    """0 = all pass, 1 = warnings only, 2 = any failures."""
    statuses = [spf["status"], dkim["status"], dmarc["status"]]
    if STATUS_FAIL in statuses:
        return 2
    if STATUS_WARN in statuses:
        return 1
    return 0


def main():
    args = parse_args()
    worst_exit = 0

    for i, domain in enumerate(args.domains):
        if i > 0:
            if args.json:
                print()
            else:
                print("\n" + ("═" * min(60, _TERM_WIDTH)) + "\n")

        spf, dkim, dmarc = run_checks(domain, args.dkim_selector)
        code = exit_code_for(spf, dkim, dmarc)
        worst_exit = max(worst_exit, code)

        if args.json:
            print_json(domain, spf, dkim, dmarc)
        else:
            print_report(domain, spf, dkim, dmarc, quiet=args.quiet)

    sys.exit(worst_exit)


if __name__ == "__main__":
    main()
