#!/usr/bin/env python3
"""
One-shot deploy runner for nurse-charles 'Before the ER' Parent Masterclass.
Run from /Users/bryce/FLSM/
"""
import json, os, shutil, subprocess, sys
from pathlib import Path
import requests
from dotenv import load_dotenv

load_dotenv()

CYCLE_DIR = Path(".tmp/briefs/nurse-charles-2026-04-20")
STATE_FILE = CYCLE_DIR / "deploy_state.json"
LANDING_SRC = CYCLE_DIR / "landing_page.html"
WEBSITE_DIR = Path(".tmp/nurse-charles-media")
PRODUCT_SLUG = "before-the-er-parent-masterclass"
PRODUCT_NAME = "'Before the ER' Parent Masterclass"
CLIENT_NAME = "Nurse Charles"
CONTACT_EMAIL = "cfolsom865@gmail.com"
ONBOARDING_URL = "https://onboarding.emersonnorth.com?lid=VMK8SyHTd8uCMgcJ7I2A&tok=5ae6346774322b02fb272159277d742c3e35d79b5ce18619e3f09cd9b13935fd"
RESEND_KEY = os.getenv("RESEND_API_KEY", "")
EN_BOT_TOKEN = os.getenv("EN_BOT_TELEGRAM_TOKEN", "")
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID_BRYCE", "")
LANDING_PAGE_URL = f"https://nursecharlesmedia.com/{PRODUCT_SLUG}"


def load_state():
    if STATE_FILE.exists():
        return json.loads(STATE_FILE.read_text())
    return {}


def save_state(state):
    STATE_FILE.write_text(json.dumps(state, indent=2))


def telegram(msg):
    if not EN_BOT_TOKEN or not TELEGRAM_CHAT_ID:
        print(f"[TELEGRAM SKIPPED - no token] {msg}")
        return
    resp = requests.post(
        f"https://api.telegram.org/bot{EN_BOT_TOKEN}/sendMessage",
        json={"chat_id": TELEGRAM_CHAT_ID, "text": msg},
        timeout=10,
    )
    ok = resp.status_code == 200
    print(f"[TELEGRAM {'ok' if ok else 'error ' + str(resp.status_code)}] {msg[:100]}")


def send_stripe_email(state):
    if state.get("stripe") in ("done", "skipped"):
        print("[STRIPE] already done/skipped, skipping")
        return state
    if state.get("stripe") == "failed" and state.get("error") == "not_connected":
        print("[STRIPE] already marked not_connected, skipping re-send")
        return state

    template = Path("Emerson North/email_templates/connect_stripe.html").read_text()
    html = (template
        .replace("{{CLIENT_NAME}}", CLIENT_NAME)
        .replace("{{PRODUCT_NAME}}", PRODUCT_NAME)
        .replace("{{ONBOARDING_URL}}", ONBOARDING_URL))

    resp = requests.post(
        "https://api.resend.com/emails",
        headers={"Authorization": f"Bearer {RESEND_KEY}", "Content-Type": "application/json"},
        json={
            "from": "noreply@mail.nursecharlesmedia.com",
            "to": [CONTACT_EMAIL],
            "subject": f"{PRODUCT_NAME} is ready to launch \u2014 connect Stripe to go live",
            "html": html,
        },
        timeout=15,
    )
    if resp.status_code in (200, 201):
        print(f"[STRIPE EMAIL] Sent to {CONTACT_EMAIL}")
        telegram(f"Stripe email sent to {CONTACT_EMAIL} — not connected, waiting on client.")
    else:
        print(f"[STRIPE EMAIL ERROR] {resp.status_code}: {resp.text[:300]}")
        telegram(f"WARNING: Failed to send Stripe email ({resp.status_code})")

    state["stripe"] = "failed"
    state["error"] = "not_connected"
    state["last_completed_step"] = "stripe_email_sent"
    save_state(state)
    return state


def deploy_landing_page(state):
    if state.get("landing_page_deploy") == "done":
        print(f"[LANDING PAGE] already deployed: {state.get('landing_page_url')}")
        return state

    dest = WEBSITE_DIR / f"{PRODUCT_SLUG}.html"
    shutil.copy2(str(LANDING_SRC), str(dest))
    print(f"[LANDING PAGE] Copied to {dest}")

    result = subprocess.run(
        ["vercel", "--prod", "--yes"],
        cwd=str(WEBSITE_DIR.resolve()),
        capture_output=True,
        text=True,
        timeout=120,
    )
    output = (result.stdout + result.stderr)[-1500:]
    print(output)

    if result.returncode != 0:
        print("[VERCEL] First attempt failed, retrying...")
        result2 = subprocess.run(
            ["vercel", "--prod", "--yes"],
            cwd=str(WEBSITE_DIR.resolve()),
            capture_output=True,
            text=True,
            timeout=120,
        )
        if result2.returncode != 0:
            print(f"[VERCEL RETRY FAILED]")
            state["landing_page_deploy"] = "failed"
            save_state(state)
            telegram(f"WARNING: Landing page deploy failed for {CLIENT_NAME}.")
            return state

    state["landing_page_deploy"] = "done"
    state["landing_page_url"] = LANDING_PAGE_URL
    state["last_completed_step"] = "landing_page_deployed"
    save_state(state)
    print(f"[LANDING PAGE] Deployed: {LANDING_PAGE_URL}")
    return state


def main():
    state = load_state()
    print(f"[DEPLOY] Starting nurse-charles deploy")

    # Step 2 — Stripe (not connected)
    state = send_stripe_email(state)

    # Step 3 — Booking: skipped for paid_product
    state["booking_page"] = "skipped"
    save_state(state)

    # Step 4 — Portal: skip until Stripe connects (need stripe_price_id)
    if state.get("portal_registration") not in ("done",):
        print("[PORTAL] Skipping — paid_product needs stripe_price_id, Stripe not connected yet")
        state["portal_registration"] = "failed"
        state["error"] = state.get("error", "") + "|portal_needs_stripe"
        save_state(state)

    # Step 5 — Landing page deploy
    state = deploy_landing_page(state)

    print(f"\n[DEPLOY] Results:")
    for k in ("stripe", "booking_page", "portal_registration", "landing_page_deploy", "landing_page_url", "error"):
        print(f"  {k}: {state.get(k)}")


if __name__ == "__main__":
    main()
