#!/usr/bin/env python3
"""Validate an email sequence JSON before it goes into an ESP. Python 3 stdlib only.

Usage:
  python3 validate_sequence.py SEQUENCE.json [--csv OUT.csv]

Checks every email for: word count, exactly one link, link host and UTM tag,
subject length (rendered with test values), preview length, spam trigger words,
dashes, merge-field fallbacks, footer compliance, sign-off. Checks the sequence for:
emails per path, minimum gap between sends, and early AI disclosure.
Exits 1 if any check fails, so it can gate a deploy.
"""
import csv
import json
import re
import sys

# Words that spam filters and skeptical owners both punish. Subjects get the strict list.
SUBJECT_BANNED = ["free", "$", "!", "act now", "urgent", "guarantee", "winner", "cash", "%",
                  "limited time", "deal", "discount", "last chance", "re:", "fwd:"]
BODY_BANNED = ["act now", "click here", "click below", "guarantee", "risk-free", "risk free", "100%",
               "limited time", "urgent", "winner", "cash", "buy now", "order now", "no obligation",
               "best price", "!!", "once in a lifetime", "double your", "earn", "as seen on",
               "dear friend", "congratulations", "revolutionary", "unlock", "seamless", "leverage"]
DASHES = ["\u2014", "\u2013"]  # em dash, en dash
MERGE = re.compile(r"\{\{\s*([a-z_]+)\s*(?:\|([^}]*))?\}\}")
URL = re.compile(r"https?://[^\s)>\"]+")


def render(text, seq):
    """Fill merge fields with test values (or fallbacks) and the longest dynamic block."""
    test = seq.get("render_test", {})
    blocks = seq.get("dynamic_blocks", {})

    def sub(m):
        name, fallback = m.group(1), m.group(2)
        if name in blocks:
            return max(blocks[name].values(), key=lambda s: len(s.split()))
        if name in test:
            return test[name]
        return fallback if fallback is not None else name.upper()
    return MERGE.sub(sub, text)


def links(body):
    """Return (literal URLs, merge fields that hold a URL, fallback URLs inside those fields)."""
    literal = URL.findall(MERGE.sub("", body))
    fields = [m for m in MERGE.finditer(body) if m.group(1).endswith("_url")]
    fallbacks = [m.group(2) for m in fields if m.group(2)]
    return literal, [m.group(0) for m in fields], fallbacks


def banned(text, words):
    """Whole-word match for words, substring match for symbols."""
    low = text.lower()
    hits = []
    for w in words:
        pat = r"\b" + re.escape(w.strip()) + r"\b" if w.strip()[:1].isalpha() and w.strip()[-1:].isalpha() else re.escape(w)
        if re.search(pat, low):
            hits.append(w.strip())
    return hits


def check_email(e, seq):
    fails, notes = [], []
    body, rbody = e["body"], render(e["body"], seq)
    words = len(rbody.split())
    if words >= seq["max_words"]:
        fails.append(f"body {words} words (limit under {seq['max_words']})")
    notes.append(f"{words}w")

    literal, url_fields, fallbacks = links(body)
    n_links = len(literal) + len(url_fields)
    if n_links != 1:
        fails.append(f"{n_links} links (need exactly 1)")
    for u in literal + fallbacks:
        if seq.get("link_host") and f"//{seq['link_host']}/" not in u:
            fails.append(f"off-domain link {u}")
    if seq.get("require_utm"):
        for u in literal:
            if f"utm_content={e['id']}" not in u:
                fails.append(f"link missing utm_content={e['id']}")

    for key in ("subject_a", "subject_b"):
        s = render(e[key], seq)
        if len(s) > seq["max_subject_chars"]:
            fails.append(f"{key} {len(s)} chars rendered: '{s}'")
        hits = banned(s, [w for w in SUBJECT_BANNED if w not in seq.get("subject_allow", [])])
        if hits:
            fails.append(f"{key} trigger words {hits}")
    notes.append(f"subj {len(render(e['subject_a'], seq))}/{len(render(e['subject_b'], seq))}c")

    lo, hi = seq["preview_chars"]
    if not lo <= len(e["preview"]) <= hi:
        fails.append(f"preview {len(e['preview'])} chars (want {lo} to {hi})")

    hits = banned(body + " " + e["preview"], BODY_BANNED)
    if hits:
        fails.append(f"body trigger words {hits}")

    all_text = " ".join([body, e["preview"], e["subject_a"], e["subject_b"], seq["footer"]])
    if any(d in all_text for d in DASHES):
        fails.append("contains an em or en dash")

    for m in MERGE.finditer(" ".join([body, e["subject_a"], e["subject_b"]])):
        if m.group(2) is None and m.group(1) not in seq.get("system_fields", []):
            fails.append(f"merge field {{{{{m.group(1)}}}}} has no fallback")

    for need in seq.get("footer_must_contain", []):
        if need not in seq["footer"]:
            fails.append(f"footer missing {need}")
    if not re.search(r"\nGeorge(\s|$)", body):
        fails.append("no 'George' sign-off")
    return fails, notes


def check_sequence(seq):
    fails = []
    by_id = {e["id"]: e for e in seq["emails"]}
    for name, path in seq["paths"].items():
        if len(path) > seq["max_emails_per_path"]:
            fails.append(f"path {name} sends {len(path)} emails (cap {seq['max_emails_per_path']})")
        days = [by_id[i]["day"] for i in path]
        for a, b, d1, d2 in zip(path, path[1:], days, days[1:]):
            if d2 - d1 < 1 and by_id[b]["send"] != "Immediately":
                fails.append(f"path {name}: {a} to {b} under 24 hours apart")
    first_ai = min((e["order"] for e in seq["emails"] if re.search(r"\bAI\b", e["body"])), default=99)
    if first_ai > seq["ai_disclosure_by_order"]:
        fails.append(f"AI first disclosed in email order {first_ai}, needs order {seq['ai_disclosure_by_order']} or earlier")
    return fails


def main():
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    seq = json.load(open(sys.argv[1], encoding="utf-8"))
    total = 0
    print(f"Sequence: {seq['name']} ({seq['sequence_id']}), {len(seq['emails'])} emails")
    for e in seq["emails"]:
        fails, notes = check_email(e, seq)
        total += len(fails)
        print(f"  {'PASS' if not fails else 'FAIL'}  {e['id']:<4} day {e['day']:>2}  {' '.join(notes)}")
        for f in fails:
            print(f"        - {f}")
    sfails = check_sequence(seq)
    total += len(sfails)
    paths = ", ".join(f"{k}={len(v)}" for k, v in seq["paths"].items())
    print(f"  {'PASS' if not sfails else 'FAIL'}  sequence  paths: {paths}; AI disclosed by order {seq['ai_disclosure_by_order']}")
    for f in sfails:
        print(f"        - {f}")
    if "--csv" in sys.argv:
        out = sys.argv[sys.argv.index("--csv") + 1]
        cols = ["id", "order", "day", "trigger", "condition", "send", "purpose", "subject_a", "subject_b",
                "preview", "cta_label", "cta_url", "word_count", "body"]
        with open(out, "w", newline="", encoding="utf-8") as fh:
            w = csv.DictWriter(fh, fieldnames=cols)
            w.writeheader()
            for e in seq["emails"]:
                literal, url_fields, _ = links(e["body"])
                row = {k: e.get(k, "") for k in cols}
                row["cta_url"] = (url_fields or literal or [""])[0]
                row["word_count"] = len(render(e["body"], seq).split())
                w.writerow(row)
        print(f"Wrote {out}")
    print(f"Result: {'ALL CHECKS PASSED' if total == 0 else f'{total} FAILURE(S)'}")
    sys.exit(1 if total else 0)


if __name__ == "__main__":
    main()
