#!/usr/bin/env python3
"""Second pass: remove inline free-browse guide links; fix mis-themed CTAs if needed."""
from __future__ import annotations

import re
import shutil
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path("/opt/guides")
BACKUP_DIR = Path(
    "/opt/guides/_backups/patreon-cta-pass2-"
    + datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
)

# Import theme builder by duplicating minimal pieces
THEME_COLORS = {
    "crimson": {
        "band": "#121212",
        "accent": "#C41E3A",
        "card_bg": "#1A1A1A",
        "card_border": "rgba(196,30,58,0.35)",
        "muted": "#B8B8B8",
        "btn_bg": "#C41E3A",
        "btn_hover": "#a81932",
        "eyebrow": "#C41E3A",
    },
    "purple": {
        "band": "#232060",
        "accent": "#a5a2e0",
        "card_bg": "#2a2870",
        "card_border": "rgba(163,160,220,0.35)",
        "muted": "#d5d3ee",
        "btn_bg": "#4a47a3",
        "btn_hover": "#333086",
        "eyebrow": "#d5d3ee",
    },
    "navy": {
        "band": "#0A2540",
        "accent": "#C4A35A",
        "card_bg": "#0D2E4C",
        "card_border": "rgba(196,163,90,0.35)",
        "muted": "#B8B8B8",
        "btn_bg": "#C4A35A",
        "btn_hover": "#a8873f",
        "eyebrow": "#C4A35A",
        "btn_text": "#0A2540",
    },
}


def build_cta(theme: str) -> str:
    c = THEME_COLORS[theme]
    btn_text = c.get("btn_text", "#ffffff")
    return f'''
<section class="patreon-join" id="join-patreon" aria-label="Join Rick and Isabella Pina Coaching on Patreon">
  <style>
    .patreon-join {{
      background: {c["band"]};
      color: #fff;
      padding: 64px 24px 72px;
      margin: 0;
      box-sizing: border-box;
      font-family: Montserrat, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
    }}
    .patreon-join *, .patreon-join *::before, .patreon-join *::after {{ box-sizing: border-box; }}
    .patreon-join__inner {{
      max-width: 1080px;
      margin: 0 auto;
      text-align: center;
    }}
    .patreon-join__eyebrow {{
      font-size: 12px;
      font-weight: 800;
      letter-spacing: 0.22em;
      text-transform: uppercase;
      color: {c["eyebrow"]};
      margin: 0 0 14px;
    }}
    .patreon-join__headline {{
      font-size: clamp(26px, 4vw, 40px);
      font-weight: 800;
      line-height: 1.15;
      margin: 0 0 18px;
      color: #fff;
    }}
    .patreon-join__body {{
      font-size: 16px;
      line-height: 1.65;
      color: {c["muted"]};
      max-width: 760px;
      margin: 0 auto 36px;
    }}
    .patreon-join__tiers {{
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 18px;
      text-align: left;
      margin: 0 0 36px;
    }}
    .patreon-join__tier {{
      background: {c["card_bg"]};
      border: 1px solid {c["card_border"]};
      border-radius: 14px;
      padding: 22px 20px 24px;
      min-height: 100%;
    }}
    .patreon-join__tier-name {{
      font-size: 13px;
      font-weight: 800;
      letter-spacing: 0.12em;
      text-transform: uppercase;
      color: {c["accent"]};
      margin: 0 0 8px;
    }}
    .patreon-join__tier-price {{
      font-size: 22px;
      font-weight: 800;
      color: #fff;
      margin: 0 0 12px;
    }}
    .patreon-join__tier-desc {{
      font-size: 14px;
      line-height: 1.55;
      color: {c["muted"]};
      margin: 0;
    }}
    .patreon-join__btn {{
      display: inline-block;
      background: {c["btn_bg"]};
      color: {btn_text} !important;
      text-decoration: none !important;
      font-weight: 800;
      font-size: 15px;
      letter-spacing: 0.04em;
      padding: 16px 28px;
      border-radius: 999px;
      border: none;
      transition: background 0.2s ease, transform 0.2s ease;
    }}
    .patreon-join__btn:hover {{
      background: {c["btn_hover"]};
      transform: translateY(-1px);
      color: {btn_text} !important;
    }}
    .patreon-join__sub {{
      margin-top: 18px;
      font-size: 13px;
      color: {c["muted"]};
    }}
    .patreon-join__sub a {{
      color: {c["accent"]} !important;
      text-decoration: underline;
      font-weight: 700;
    }}
    @media (max-width: 900px) {{
      .patreon-join__tiers {{ grid-template-columns: 1fr; }}
      .patreon-join {{ padding: 48px 18px 56px; }}
    }}
    @media print {{
      .patreon-join {{ display: none !important; }}
    }}
  </style>
  <div class="patreon-join__inner">
    <p class="patreon-join__eyebrow">COACHING &amp; MENTORSHIP</p>
    <h2 class="patreon-join__headline">Get coached by Rick &amp; Isabella Piña.</h2>
    <p class="patreon-join__body">If you are not a member of our Patreon, join today. Coaching and mentorship designed to maximize your potential, increase your personal productivity, and fulfill your life's purpose. Weekly teaching, a private community, and one-on-one coaching calls, all on Patreon.</p>
    <div class="patreon-join__tiers">
      <div class="patreon-join__tier">
        <div class="patreon-join__tier-name">LIBRARY TIER</div>
        <div class="patreon-join__tier-price">$25/month</div>
        <p class="patreon-join__tier-desc">Hundreds of videos and weekly teaching on life, faith, family, business, and relationships. Private Grace Life Discord, early access, and bonus episodes.</p>
      </div>
      <div class="patreon-join__tier">
        <div class="patreon-join__tier-name">MONTHLY 1:1 MEETINGS</div>
        <div class="patreon-join__tier-price">$100/month</div>
        <p class="patreon-join__tier-desc">Everything in Library, plus a monthly one-on-one phone call with Rick or Isabella (coaching, prayer, personal or business guidance) and direct Q&amp;A access.</p>
      </div>
      <div class="patreon-join__tier">
        <div class="patreon-join__tier-name">DIRECT COACHING</div>
        <div class="patreon-join__tier-price">$500/month</div>
        <p class="patreon-join__tier-desc">Monthly one-on-one video coaching sessions with Rick or Isabella, direct Q&amp;A access, and the full content library.</p>
      </div>
    </div>
    <a class="patreon-join__btn" href="https://www.patreon.com/rickpina" target="_blank" rel="noopener">Join on Patreon →</a>
    <p class="patreon-join__sub">Rick &amp; Isabella Piña Coaching on Patreon · <a href="https://www.patreon.com/rickpina" target="_blank" rel="noopener">patreon.com/rickpina</a></p>
  </div>
</section>
'''.strip() + "\n"


GUIDE_HTML_HREF = re.compile(
    r'https?://guides\.rickpina\.cloud/[^"\'\s<>]*?(?:premium-guide[^"\'\s<>]*|/vcmi/[^"\'\s<>]+|/jpm-9-books/[^"\'\s<>]+)?\.html',
    re.I,
)

# Broader: any guides.rickpina.cloud HTML page link (not pdf/png)
OTHER_GUIDE_PAGE = re.compile(
    r'https?://guides\.rickpina\.cloud/(?!$)(?![^"\s]+\.(?:pdf|png|jpg|jpeg|webp|mp3|mp4|og\.png))[^"\s#?]+\.html',
    re.I,
)


def is_self_link(href: str, page: Path) -> bool:
    name = page.name
    stem = page.parent.name if name == "index.html" else page.stem
    return stem in href or name in href


def remove_inline_other_guide_links(html: str, page: Path) -> str:
    """Remove anchors to other guides HTML pages; drop empty Related/Go deeper wrappers."""

    def a_repl(m: re.Match) -> str:
        full = m.group(0)
        href = m.group(1)
        # Keep OG/meta is outside body anchors; this only matches <a>
        if not re.search(r"guides\.rickpina\.cloud", href, re.I):
            return full
        # Keep same-page PDF already handled by not matching .html only
        if re.search(r"\.(pdf|png|jpg|jpeg|webp|mp3|mp4)(\?|$)", href, re.I):
            return full
        # Keep self HTML
        if is_self_link(href, page):
            return full
        # Keep VCMI series links only in footers (handled separately) — strip body farms
        # Keep JPM series prev/next in body (same series navigation)
        if "/jpm-9-books/" in href and "/jpm-9-books/" in str(page):
            return full
        if any(
            s in href
            for s in (
                "/vcmi/its-bigger-than-you/",
                "/vcmi/living-legacy-minded-part-2/",
                "/vcmi/god-builds-families/",
                "/vcmi/its-bigger-than-you-bible-study/",
            )
        ) and "/vcmi/" in str(page):
            # Only keep if we're on a series page
            return full
        # Remove other guide HTML / directory pages used as free browse
        if href.endswith(".html") or re.search(r"guides\.rickpina\.cloud/.+/?", href):
            # directory hubs under guides
            if re.search(r"\.(pdf|png|jpg|jpeg|webp|mp3|mp4)(\?|$)", href, re.I):
                return full
            if href.rstrip("/").endswith("guides.rickpina.cloud"):
                return ""
            # Remove HTML guide cross-links
            if href.endswith(".html") or "/premium-guide" in href:
                return ""
            # Remove other free hubs except jpm series already kept
            if "/vcmi/" in href and "/vcmi/" in str(page):
                # non-series vcmi cross links in body
                return ""
        return full

    html2 = re.sub(r'(?is)<a\s+[^>]*href="([^"]+)"[^>]*>.*?</a>', a_repl, html)

    # Remove empty "Related: ." / "Go deeper: ." / "See also: ." / "Pair this lesson..." leftover
    patterns = [
        r"(?is)<p>\s*Related:\s*(?:and\s*)?[.\s]*</p>\s*",
        r"(?is)<p>\s*See also:\s*[.\s]*</p>\s*",
        r"(?is)<p>\s*Pair this lesson with the full curated guide:\s*[.\s]*</p>\s*",
        r"(?is)<li><strong>Go deeper:</strong>\s*(?:,\s*)*\.?</li>\s*",
        r"(?is)<li><strong>Go deeper:</strong>\s*</li>\s*",
        # cleanup dangling "Related: and ." etc inside remaining p
        r"(?is)(Related:|See also:|Go deeper:)\s*(?:and\s*)?(?:,\s*)*\.?",
    ]
    for pat in patterns[:5]:
        html2 = re.sub(pat, "", html2)

    # Clean list items that became "Go deeper: , , ."
    def clean_go_deeper(m: re.Match) -> str:
        inner = m.group(0)
        # if no remaining <a>, remove whole li
        if "<a " not in inner and "<a\n" not in inner:
            return ""
        # tidy commas
        inner = re.sub(r"(?is)(<strong>Go deeper:</strong>)\s*[,\s]*", r"\1 ", inner)
        inner = re.sub(r"\s*,\s*,+", ", ", inner)
        inner = re.sub(r"\s*,\s*\.</li>", ".</li>", inner)
        inner = re.sub(r"\s*,\s*</li>", ".</li>", inner)
        return inner

    html2 = re.sub(r"(?is)<li><strong>Go deeper:</strong>.*?</li>", clean_go_deeper, html2)

    # Clean paragraphs that are only "Related: and ." leftovers
    def clean_related_p(m: re.Match) -> str:
        block = m.group(0)
        if "<a " not in block:
            return ""
        block = re.sub(r"(?is)(Related:|See also:)\s*(?:and\s*)?", r"\1 ", block)
        block = re.sub(r"\s+and\s+\.", ".", block)
        block = re.sub(r"\s*,\s*\.", ".", block)
        return block

    html2 = re.sub(
        r"(?is)<p>\s*(?:Related:|See also:|Pair this lesson with the full curated guide:).*?</p>",
        clean_related_p,
        html2,
    )

    # Checklist lines that only linked to another guide — remove the empty <a> leftovers already gone;
    # if the checklist item is ONLY a cross-guide link, leave the text without the link (already done).
    return html2


def detect_theme_strict(path: Path, html: str) -> str:
    """Prefer path, then CSS variables near :root, not body content."""
    rel = str(path.relative_to(ROOT)).replace("\\", "/")
    if rel.startswith("vcmi/"):
        return "purple"
    if rel.startswith("jpm-9-books/"):
        return "navy"

    # Prefer :root / early style block vars
    head = html[:8000]
    if re.search(r"--crimson\s*:\s*#C41E3A|--color-accent\s*:\s*#C41E3A", head, re.I):
        return "crimson"
    if re.search(r"--purple\s*:\s*#333086|#333086|#232060", head, re.I):
        return "purple"
    if re.search(r"--color-bg-dark\s*:\s*#0A2540|--color-accent\s*:\s*#C4A35A", head, re.I):
        return "navy"
    if "#C41E3A" in head or "#c41e3a" in head or "--crimson" in head:
        return "crimson"
    if "#0A2540" in head or "#0a2540" in head:
        return "navy"
    if "#333086" in head or "#232060" in head:
        return "purple"

    # Known outliers
    name = path.name.lower()
    if "marriage" in name or "marriage" in rel:
        # marriage-bible and what-is-your-marriage use navy/gold in early CSS?
        if "#0A2540" in html[:12000] or "#C4A35A" in html[:12000]:
            return "navy"
    return "crimson"


def replace_cta(html: str, theme: str) -> str:
    cta = build_cta(theme)
    html = re.sub(
        r"(?is)\s*<section class=\"patreon-join\"[^>]*>.*?</section>\s*",
        "\n",
        html,
        count=1,
    )
    m = re.search(r"(?i)<footer\b", html)
    if m:
        return html[: m.start()] + "\n" + cta + "\n" + html[m.start() :]
    m = re.search(r"(?i)</body\s*>", html)
    if m:
        return html[: m.start()] + "\n" + cta + "\n" + html[m.start() :]
    return html + "\n" + cta


def process(path: Path) -> dict:
    original = path.read_text(encoding="utf-8", errors="replace")
    html = original
    changes = []

    before = html
    html = remove_inline_other_guide_links(html, path)
    if html != before:
        changes.append("inline-farms")

    theme = detect_theme_strict(path, html)
    # Re-theme CTA always with stricter detection
    html2 = replace_cta(html, theme)
    if html2 != html:
        changes.append(f"retheme-{theme}")
    html = html2

    if html == original:
        return {"path": str(path), "changed": False, "theme": theme, "changes": []}

    BACKUP_DIR.mkdir(parents=True, exist_ok=True)
    rel = path.relative_to(ROOT)
    bak = BACKUP_DIR / rel
    bak.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(path, bak)
    path.write_text(html, encoding="utf-8")
    return {"path": str(path), "changed": True, "theme": theme, "changes": changes}


def main():
    files = [
        p
        for p in ROOT.rglob("*.html")
        if "ripm" not in p.parts and "/_backups/" not in str(p) and p.stat().st_size >= 50
    ]
    updated = []
    for p in sorted(files):
        res = process(p)
        if res["changed"]:
            updated.append(res)

    print("BACKUP", BACKUP_DIR)
    print("UPDATED", len(updated))
    for r in updated:
        print(f"{r['theme']:7} {','.join(r['changes']):40} {r['path']}")

    # remaining farms
    print("\n==== remaining premium-guide.html links (non-meta) ====")
    for p in sorted(files):
        t = p.read_text(errors="replace")
        # strip meta/link head roughly
        body = t
        if "<body" in t.lower():
            body = t[t.lower().find("<body") :]
        n = len(
            re.findall(
                r'href="https://guides\.rickpina\.cloud/[^"]*premium-guide[^"]*\.html"',
                body,
            )
        )
        if n:
            print(n, p)


if __name__ == "__main__":
    main()
