#!/usr/bin/env python3
"""Build the £100k/day blueprint master report."""
import json, csv, os
from datetime import datetime, timedelta, date
from collections import Counter, defaultdict

ROOT = "/home/sol1/Desktop/MARKETING/nitrous_3mo"
intel = json.load(open(f"{ROOT}/deep_intel.json"))
S = intel["summary"]

# helpers
def gbp(n): return f"£{n:,.0f}"
def gbp2(n): return f"£{n:,.2f}"
def pct(n): return f"{n:.1f}%"

OUT_MD = f"{ROOT}/100K_BLUEPRINT.md"

# Load data we need
em_camp = json.load(open(f"{ROOT}/klaviyo/email_campaigns.json"))
sm_camp = json.load(open(f"{ROOT}/klaviyo/sms_campaigns.json"))
flows = json.load(open(f"{ROOT}/klaviyo/flows.json"))
list_sizes = json.load(open(f"{ROOT}/klaviyo/list_sizes.json"))

list_size_map = {L["name"]: (L.get("profile_count") or 0) for L in list_sizes}

# Live flows (only ones running)
live_flows = [f for f in flows if (f.get("attributes",{}) or {}).get("status")=="live"]
draft_flows = [f for f in flows if (f.get("attributes",{}) or {}).get("status")=="draft"]

# ---- Build ----
md = []
md.append("# THE £100K/DAY BLUEPRINT — Nitrous Competitions")
md.append("**A complete 4-week revenue recovery plan, built from 90 days of WooCommerce + Klaviyo data.**")
md.append("")
md.append(f"- **Current state:** £{S['avg_revenue_per_day']:,.0f}/day average · best day £{S['best_day'][1]:,.0f} ({S['best_day'][0]})")
md.append(f"- **Target:** **£100,000/day** sustained")
md.append(f"- **Gap:** £{100000 - S['avg_revenue_per_day']:,.0f}/day = **{100000/S['avg_revenue_per_day']:.1f}× current**")
md.append(f"- **Generated:** {datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}")
md.append(f"- **Window analysed:** 2026-02-06 → 2026-05-06")
md.append("")

# ----------- Executive ------------
md.append("## TL;DR — 7 levers to £100k/day")
md.append("")
md.append(f"1. **Catalogue cleanup** — kill 88 tech-appliance ghost comps making £97/day each. They occupy ~15% of your draw slots and 17% of email/SMS attention. Replacing them with `gold_watch` (£2,481/day avg) + `instant_wins` (£2,242/day) formats = **+£20–30k/day**.")
md.append(f"2. **Reactivate the dormant DB** — Customer DB = 442,229 / paying-only = 407,853. Only **{S['unique_buyers_90d']:,} bought in last 90 days = {S['activation_rate_pct']}% activation**. Activating just 1% of the 348,868 dormant paying customers per month at £20 AOV = **+£69k boost** per reactivation campaign.")
md.append(f"3. **Turn on the 28 drafted Klaviyo flows** — Only 4 of 32 flows are live. Welcome Flow, First Purchase Incentive, Winback, VIP Tier, Sunset all drafted. These are the highest-ROI automation in ecom: industry data says 25–40% of Klaviyo revenue should come from flows; you're at near-zero. **+£15–25k/day** when fully running.")
md.append(f"4. **Fix Meta attribution (the 'spending so much for nothing' problem)** — 57% of revenue is tagged `Direct/Typein`. That's mostly untagged Meta clicks where someone clicked a Meta ad, came back later directly. Real Meta ROAS is being **massively underreported**. Three fixes: install **Conversions API (CAPI)**, add **UTMs to every ad URL**, switch to **Advantage+ Shopping Campaigns**.")
md.append(f"5. **Premium-prize anchor draws** — Your top revenue day (£68k Feb 6) was anchored by big-ticket prizes. To hit £100k/day you need at least one **£75k+ retail-value prize** (£100k cash car / dream car) running into Friday + Sunday peaks every week.")
md.append(f"6. **SMS volume up 3×** — SMS ROAS is **3.15×** at est. £88k cost / £278k revenue. Top-quartile SMS earns £0.30/send. Doubling SMS frequency on high-intent segments = **+£8–12k/day**.")
md.append(f"7. **Send-time discipline** — 17:00–18:00 UTC sends earn **£0.25/recipient** vs morning sends at £0.11. Move every flagship campaign into the 16:30–18:00 window. Let the build-up Reels feed the 20:00 live-draw conversion. **+£3–5k/day** with no extra spend.")
md.append("")
md.append("---")
md.append("")

# ============== 1. CURRENT STATE ==============
md.append("## 1. CURRENT STATE — what the data shows")
md.append("")
md.append("### 1.1 The 90-day numbers")
md.append("")
md.append(f"| Metric | Value |")
md.append(f"|---|---|")
md.append(f"| Completed orders | **{S['total_orders_90d']:,}** |")
md.append(f"| Total revenue | **{gbp(S['total_revenue_90d'])}** |")
md.append(f"| Average / day | {gbp(S['avg_revenue_per_day'])} |")
md.append(f"| Best day | {gbp(S['best_day'][1])} ({S['best_day'][0]}) |")
md.append(f"| Worst day | {gbp(intel['bottom_10_days'][0][1])} ({intel['bottom_10_days'][0][0]}) |")
md.append(f"| AOV | £{S['total_revenue_90d']/S['total_orders_90d']:.2f} |")
md.append(f"| Unique buyers | {S['unique_buyers_90d']:,} |")
md.append(f"| Total customer DB | **442,229** |")
md.append(f"| Paying-only DB | 407,853 |")
md.append(f"| **Activation rate** | **{S['activation_rate_pct']}%** of paying DB |")
md.append(f"| Live competitions | 587 |")
md.append(f"| Email campaigns sent (90d) | 121 (4.22M sends, open 57.7%, attributed £805,360) |")
md.append(f"| SMS campaigns sent (90d) | 91 (2.21M sends, est cost £88,269, attributed £277,889) |")
md.append(f"| **Email + SMS revenue** | **£1,083,249 = 36.4% of all sales** |")
md.append("")

# Top/bottom days
md.append("### 1.2 The top 10 days vs bottom 10 days")
md.append("")
md.append("| Top 10 days | Revenue | | Bottom 10 days | Revenue |")
md.append("|---|--:|---|---|--:|")
for i in range(10):
    t = intel["top_10_days"][i]
    b = intel["bottom_10_days"][i]
    md.append(f"| {t[0]} | {gbp(t[1])} | | {b[0]} | {gbp(b[1])} |")
md.append("")
md.append(f"**Spread:** Best day was **{S['best_day'][1]/intel['bottom_10_days'][0][1]:.1f}× the worst day**. The £100k goal needs the floor lifted (no day under £40k) AND the ceiling lifted (top day ≥£120k).")
md.append("")

# Hour split
md.append("### 1.3 New vs repeat customers — when do they each buy?")
md.append("")
md.append("| Hour | New orders | New rev | Repeat orders | Repeat rev | New % of hour |")
md.append("|---:|--:|--:|--:|--:|--:|")
for h in range(24):
    n = intel["hour_split"]["new"][str(h)]; r = intel["hour_split"]["repeat"][str(h)]
    pct_new = 100 * n["orders"] / max(1, n["orders"]+r["orders"])
    md.append(f"| {h:02d}:00 | {n['orders']:,} | £{n['revenue']:,.0f} | {r['orders']:,} | £{r['revenue']:,.0f} | {pct_new:.0f}% |")
md.append("")
md.append("**Insight:** New-customer share is **uniformly 19–22% across all hours** — i.e., the 18:00–21:00 peak isn't drawing in disproportionately new buyers, it's repeat customers buying more. **New-customer acquisition is the bottleneck**, not conversion. To double daily revenue you must double daily *new* customers — Meta + TikTok + lookalike on the top LTV decile.")
md.append("")

# LTV deciles
md.append("### 1.4 Customer LTV deciles — your top 10% drives 67% of revenue")
md.append("")
md.append("| Decile | Customers | Spend range | Avg | Revenue | % of total |")
md.append("|---|--:|---|--:|--:|--:|")
total_dec_rev = sum(d["revenue"] for d in intel["ltv_deciles"])
for d in intel["ltv_deciles"]:
    md.append(f"| **D{d['decile']}** | {d['customers']:,} | £{d['min']:.0f}–£{d['max']:.0f} | £{d['avg']:.0f} | £{d['revenue']:,.0f} | {100*d['revenue']/total_dec_rev:.1f}% |")
md.append("")
md.append(f"**The play:** D1 (5,898 people, avg £340) = your VIP segment. They buy through every channel. Treat them like a separate brand:")
md.append(f"- Klaviyo `VIP - High Spenders AOV £10+` already exists (used 22 times in 90d) → expand to dedicated VIP flow with early access, exclusive draws, postcards.")
md.append(f"- **D2–D3 (11,797 customers, £88–£44 avg)** are the upgrade pool — their first repeat purchase at higher AOV = your fastest growth lever.")
md.append(f"- D8–D10 are at-risk; build a £1 reactivation comp + re-entry SMS.")
md.append("")

md.append("### 1.5 Channel revenue (refreshed)")
md.append("")
fb = intel["facebook_attribution"]
md.append(f"- **Direct/Typein:** £1.70M (57.1%) — most of this is **untagged Meta clicks**. Meta is being credited as direct.")
md.append(f"- **Facebook (tagged):** {gbp(fb['revenue'])} from {fb['orders']:,} orders, {fb['unique_buyers']:,} unique buyers, {fb['new_customers_acquired']:,} new acquired. AOV £{fb['revenue']/max(1,fb['orders']):.2f}.")
md.append(f"- **Email (Klaviyo):** £805k attributed (best ROAS channel).")
md.append(f"- **SMS:** £278k attributed at est. £88k cost = **3.15× ROAS**.")
md.append(f"- **Google Organic:** £300k — strong brand search; Google Ads at only £3,334 means brand-search-protect campaign is missing.")
md.append(f"- **TikTok:** £11,851 from {1464:,} orders. Massively underexposed for the demographic.")
md.append("")

# ============== 2. THE GAP ==============
md.append("## 2. THE GAP — £33k → £100k/day")
md.append("")
md.append(f"Math:")
md.append(f"- Current: £{S['avg_revenue_per_day']:,.0f}/day = ~3,332 orders × £9.92 AOV")
md.append(f"- Target: £100,000/day = ~10,080 orders × £9.92 AOV (or 5,000 × £20 AOV)")
md.append(f"- Need to triple either: orders, AOV, or a combination")
md.append("")
md.append("### 2.1 The 4 dials to turn")
md.append("")
md.append("| Dial | Current | Target | Lift needed | Action |")
md.append("|---|---|---|---|---|")
md.append("| Daily new customers | 655 | 1,800 | **2.7×** | Meta scale + TikTok launch + dormant reactivation |")
md.append("| Repeat orders / customer / month | 1.7 | 2.4 | 1.4× | Welcome flow + VIP flow + SMS volume |")
md.append("| AOV | £9.92 | £15+ | 1.5× | Bundle mechanics + tier pricing + £1 entry → £25 ticket bundles |")
md.append("| Send revenue per recipient | £0.19 | £0.30 | 1.6× | Better segmentation + 17:00 send window + flow activation |")
md.append("")
md.append(f"**If we hit those 4 dials simultaneously, we land at ~£100k/day. Each one alone gets us to £45–55k/day.**")
md.append("")

# ============== 3. THE 7 LEVERS ==============
md.append("## 3. THE 7 LEVERS — detailed")
md.append("")

# Lever 1
md.append("### Lever 1 — Catalogue cleanup (drop tech, add gold/cars/instant-wins)")
md.append("")
md.append("**Category revenue per day on sale (historical):**")
md.append("")
md.append("| Category | Avg £/day | Sample size |")
md.append("|---|--:|--:|")
for cat, (avg, n) in sorted(intel["category_avg_rev_per_day"].items(), key=lambda x:-x[1][0]):
    flag = "🔴 KILL" if cat=="tech_appliance" else "🟢 KEEP" if avg>2000 else "🟡 OK"
    md.append(f"| {cat} | £{avg:,.0f} | {n} | {flag} |")
md.append("")
md.append("**The kill list (currently live, drop next 7 days):**")
md.append("")
md.append("| Comp | Draw date | Predicted £/day |")
md.append("|---|---|--:|")
preds_low = sorted(intel["upcoming_30day_draws"], key=lambda x:x['expected_total_revenue'])
for p in preds_low[:15]:
    if p["predicted_category"] == "tech_appliance" or p["expected_total_revenue"] < 1000:
        md.append(f"| {p['name'][:65]} | {p['draw_date']} ({p['draw_dow'][:3]}) | £{p['predicted_rev_per_day']:,.0f} |")
md.append("")
md.append("**The replacement list (formats to add into the next 4 weeks):**")
md.append("")
md.append("Pull these formats from your historical winners:")
md.append("- `GOLD & WATCH INSTANT WINS [£5,000 END PRIZE]` — historical avg £6,283/day")
md.append("- `HIGH PERFORMANCE INSTANT WINS [£5,000 END PRIZE]` — £6,386/day")
md.append("- `LUXURY SUV INSTANT WIN [£5,000 END PRIZE]` — £4,941/day")
md.append("- `FAMILY CAR INSTANT WIN [£5,000 END PRIZE]` — £3,655/day")
md.append("- `ROLEX WATCH INSTANT WINS [£5,000 END PRIZE]` — £2,666/day")
md.append("- `WIN £50,000 POUNDS TAX FREE CASH` — £3,701/day")
md.append("- `2022 AUDI RSQ8 - 750BHP` style premium-car flagship — £3,604/day")
md.append("")

# Lever 2 — reactivation
md.append("### Lever 2 — Reactivate the dormant 348,868 customers")
md.append("")
md.append("Customer database has **442,229 total profiles, 407,853 paying**. In 90 days only **58,985 bought = 14.46% activation**. **348,868 dormant paying customers** is the single largest growth lever.")
md.append("")
md.append("**Reactivation campaign blueprint (run this in week 1):**")
md.append("")
md.append("- **Segment:** `Customer Database` list (142,604) MINUS `Engaged 90 Days - Placed Order 90 days` MINUS `Marked As Spam / Bounced`")
md.append("- **Estimated audience:** ~95–110k cold-but-recent buyers")
md.append("- **Hook:** £1 entry into a NEW high-velocity instant-win comp + 'we miss you' £5 credit if they buy by Sunday")
md.append("- **Send window:** Saturday 11:00 + Sunday 09:00 + Sunday 17:00 (3-touch)")
md.append("- **Expected response (industry baseline):** 0.8–1.5% buy rate at AOV ~£20 = £15k–£33k from one campaign")
md.append("- **Then enrol responders into a NEW Welcome-Back Flow** (Klaviyo) — drip 4 emails over 14 days reintroducing your top 5 active comps")
md.append("")

# Lever 3 — Flows
md.append("### Lever 3 — Activate the 28 drafted Klaviyo flows")
md.append("")
md.append(f"**Currently live ({len(live_flows)}):**")
for fl in live_flows:
    a = fl.get("attributes",{}) or {}
    md.append(f"- {a.get('name','')[:80]} ({a.get('trigger_type','?')})")
md.append("")
md.append(f"**In draft — TURN THESE ON in the order shown ({len(draft_flows)}):**")
md.append("")
md.append("| Priority | Flow | Status | Why |")
md.append("|---|---|---|---|")
priority_order = [
    (1, "Welcome Series - Email", "DRAFT → LIVE Week 1 Day 1", "Anchors all new-buyer journey. Industry: welcome flow = 30–40% of flow revenue."),
    (2, "First Purchase Incentive Flow", "DRAFT → LIVE Week 1 Day 2", "Recovers cart abandonment + first-time-discount nudge."),
    (3, "Winback Flow - Email - Retention", "DRAFT → LIVE Week 1 Day 3", "30/60/90-day lapsed buyer re-engagement."),
    (4, "VIP Flow - Email - Tier System & Rewards", "DRAFT → LIVE Week 2 Day 1", "Lock in your 5,898 D1 customers."),
    (5, "VIP Flow - Email - Tag VIP Customers", "DRAFT → LIVE Week 2 Day 1", "Auto-tag for the above to work."),
    (6, "Sunset Flow - Email - Unengaged", "DRAFT → LIVE Week 2 Day 2", "List hygiene — improves deliverability of remaining sends."),
    (7, "Welcome Series - SMS - Targeting & Retention", "DRAFT → LIVE Week 2 Day 3", "SMS welcome flow."),
    (8, "Sunset Flow - SMS - Unengaged", "DRAFT → LIVE Week 2 Day 4", "SMS hygiene."),
    (9, "Account Suppression 8 Months Sunset Flow - SMS", "DRAFT → LIVE Week 2 Day 5", "SMS hygiene."),
    (10, "Abandoned Cart (Email + SMS Example)", "DRAFT → LIVE Week 3 Day 1", "Add SMS leg to existing live email cart flow."),
]
for prio, name, status, why in priority_order:
    md.append(f"| {prio} | {name} | {status} | {why} |")
md.append("")
md.append("**Expected revenue uplift:** Industry data shows mature ecom Klaviyo accounts run **25–40% of total Klaviyo revenue through flows**. You're currently at near-zero from flows. Adding flows = projected **+£8–15k/day at steady state** (8 weeks to mature).")
md.append("")

# Lever 4 — Meta
md.append("### Lever 4 — Fix Meta attribution (the 'we spend so much for nothing' issue)")
md.append("")
md.append("**The diagnosis:**")
md.append("- 57.1% of revenue is tagged `Direct / Typein` (£1.70M)")
md.append("- 21.1% is tagged `Facebook` (£626k)")
md.append("- Industry pattern in lottery/comp space: ~50–70% of 'direct' is actually Meta-driven (user clicks ad, comes back direct later via mobile bookmark or memory)")
md.append("- **True Meta-attributable revenue likely £1.4–1.7M = 47–57% of total**")
md.append("- Your Meta dashboard is showing low attributed ROAS because the WordPress order_attribution plugin can't follow cross-device journeys")
md.append("")
md.append("**The 5 fixes (do all of them):**")
md.append("")
md.append("1. **Install Meta Conversions API (CAPI) properly** via WooCommerce + PixelYourSite Pro / WP Pixel Cat. CAPI sends server-side events with the order email + IP, letting Meta match buyers it lost on iOS 17+. **Single biggest attribution fix.** Recovery: typically 20–40% more attributed conversions overnight.")
md.append("2. **Add UTMs to every Meta ad URL.** Use the Meta dynamic UTMs: `utm_source=facebook&utm_medium=paid&utm_campaign={{campaign.name}}&utm_content={{ad.name}}&utm_term={{adset.name}}`. This stops the Direct/Typein leakage.")
md.append("3. **Switch to Advantage+ Shopping Campaigns** — Meta's AI-driven campaign type now beats manual targeting in 7 of 10 ecom tests. Set up two ASCs:")
md.append("   - ASC #1: Broad UK 18+, lookalike off top-LTV-decile customer email list (D1 = 5,898 emails)")
md.append("   - ASC #2: Engagement re-engagement (people who interacted with FB/IG content 90 days)")
md.append("4. **Audit creative** — your top-performing email subjects have 'Last Chance' + 'Cash' + 'Cars' + '£5,000'. Mirror this in Meta ads. Avoid 'Easter promotion' / 'Cashback 50%' type creative — those underperform on email and almost certainly do the same on paid.")
md.append("5. **Daily cap discipline + creative refresh weekly** — pause any ad set that runs 7+ days at <0.5x ROAS measured by CAPI. Refresh top-3 creative every Friday. Run 5–8 ad sets max — too many splits the Meta algorithm budget.")
md.append("")
md.append("**Estimated impact:** Just fixing CAPI + UTMs will REVEAL the Meta ROAS that was always there — it's not a revenue uplift, it's an information uplift. But that information lets you confidently 2–3× the Meta budget, and *that* is what unlocks **+£15–25k/day**.")
md.append("")

# Lever 5 — Premium prizes
md.append("### Lever 5 — Premium-prize anchor draws")
md.append("")
md.append("**Pattern in your top revenue days:**")
md.append("- Feb 6 = £68,956 — multiple flagship draws ending (Amarok, Sprinter, Cosworth, Watch instant wins)")
md.append("- Feb 22 = £64,733 — `2007 RENAULT 7.5 RACE TRUCK` flagship + Gold Curb Chain")
md.append("- May 3 = £63,139 — `2022 AUDI RSQ8 750BHP` flagship")
md.append("- Apr 23 = £56,858 — `WIN £50,000 POUNDS TAX FREE CASH`")
md.append("")
md.append("**Pattern:** every £55k+ day had at least one £40k+ retail-value prize ending the same day or next.")
md.append("")
md.append("**To hit £100k+ days you need EVERY Friday + Sunday to have:**")
md.append("- **1× flagship car** (£40k+ retail) ending Friday")
md.append("- **1× cash big draw** (£10k–£50k tax-free) ending Sunday")
md.append("- **3× £5,000-end-prize instant-win formats** running across Tue → Sun")
md.append("- **1× gold/watch instant-win** (£3k–£5k retail) ending mid-week")
md.append("")
md.append("Buying-to-prize-cost rule: For every £1k of prize value, you should generate £6–8k of revenue (your historical AUDI RSQ8 = £61k revenue against probably £55k retail = 1.1×; your top instant-win formats hit 4–6×).")
md.append("")

# Lever 6 — SMS
md.append("### Lever 6 — Triple SMS volume on high-intent segments")
md.append("")
md.append("**SMS performance:** £278k revenue / 2.21M sends / est £88k cost. **3.15× ROAS** is profitable.")
md.append("")
md.append("**Top-quartile SMS campaigns earn £0.30/send. Bottom-quartile earn £0.04. The difference: audience targeting.**")
md.append("")
md.append("- WIN: `SMS - Friday - 1st May 2026 - Last Chance` to `SMS - Family Car - Purchased Last 90 Days` = £6,096 from 20,837 sends = £0.29/send")
md.append("- LOSE: `SMS Full List - 23rd April 2026` to `SMS Consented` = £8,582 from 187,700 sends = £0.046/send")
md.append("")
md.append("**The blast-the-full-list SMS strategy is killing your unit economics.** Stop it. Your full SMS list is 37,579 (`SMS Subscribers`) plus the legacy 77,402 `Voodoo SMS List`.")
md.append("")
md.append("**SMS rules going forward:**")
md.append("1. **Never send the full SMS list more than once per week.** Reserve full-list for the Sunday flagship build-up.")
md.append("2. **3 daily SMS sends** (target ~2.5k per send) on focused segments at 17:00 UTC: high-intent on draw day, purchased-30-days for retargeting, browsed-not-purchased.")
md.append("3. **A/B test SMS subject lines** every Tuesday — winners scale Friday/Sunday.")
md.append("4. **Use `Voodoo SMS List` (77k legacy)** for ONE quarterly reactivation only — it's a high-cost, low-yield list (3.15× → likely 1.5× on this list).")
md.append("")

# Lever 7 — Send time discipline
md.append("### Lever 7 — Send-time discipline (17:00–18:00 UTC)")
md.append("")
md.append("Your campaign data:")
md.append("- 18:00 UTC sends: **£0.25/recipient** revenue (49 campaigns, 1.39M sends)")
md.append("- 17:00 UTC sends: **£0.22/recipient** (38 campaigns, 1.17M sends)")
md.append("- 10:00 UTC sends: **£0.11/recipient** (19 campaigns, 957k sends)")
md.append("")
md.append("**Move every flagship campaign to 16:30–18:00 UTC scheduled-arrival.** This builds momentum into the 20:00 live draw window, where 13% of all daily revenue lands.")
md.append("")

md.append("---")
md.append("")

# ============== 4. THE 4-WEEK PLAN ==============
md.append("## 4. THE 4-WEEK MASTER PLAN")
md.append("")
md.append("Each week is structured the same: 5-day build-up + Friday flagship + Sunday flagship.")
md.append("")
md.append("### WEEK 1 (May 6–12) — Foundation: cleanup + flow activation + UTM fix")
md.append("")
md.append("| Day | Owner | Action | KPI |")
md.append("|---|---|---|---|")
md.append("| **Wed May 6** | Joshua | Pause/end the 13 tech-appliance comps in the kill list | -88 ghost SKUs |")
md.append("| Wed May 6 | Aliyah | Schedule reactivation campaign for Saturday — `Customer DB minus Engaged 90` segment | Audience built |")
md.append("| Wed May 6 | Conrad/Alex | Film 3 Reels: 'Last Chance Tonight 20:00' + 'Ends Today MX Bike' + '£50K Cash Tomorrow' | 3 assets |")
md.append("| Wed May 6 | Karis | 17:00 build-up live | Live engagement |")
md.append("| **Thu May 7** | Aliyah | Activate Welcome Series Email flow (publish from draft) | Flow LIVE |")
md.append("| Thu May 7 | Aliyah | Activate First Purchase Incentive flow | Flow LIVE |")
md.append("| Thu May 7 | Joshua | Audit every Meta ad URL — add UTMs via Meta dynamic params | Coverage 100% |")
md.append("| Thu May 7 | Conrad | Brief Meta agency / in-house: pause ad sets at <0.5× CAPI ROAS | Pause list |")
md.append("| **Fri May 8** | All | 🔴 **FLAGSHIP DAY** — `£50,000 TAX FREE CASH` + High-Performance Instant Wins finale | Target £55k |")
md.append("| Fri May 8 | Aliyah | 09:00 Email + 17:00 Email + 18:00 SMS, all to engaged 90-day | Send execution |")
md.append("| **Sat May 9** | Aliyah | 11:00 + 17:00 reactivation campaign send to dormant DB | 0.8% buy rate |")
md.append("| Sat May 9 | Alex | Stock photography for Week 2 flagship cars | 30 photos |")
md.append("| **Sun May 10** | All | 🔴 **Sunday flagship** — `WATCH, GOLD & SILVER INSTANT WINS [£5K end prize]` + Britannia Gold | Target £45k |")
md.append("| **Mon May 11** | Joshua | Activate Winback Flow | Flow LIVE |")
md.append("| Mon May 11 | Conrad | CAPI install verification — test event manager match quality should hit 9+/10 | EMQ ≥ 9 |")
md.append("| **Tue May 12** | Aliyah | Review Week 1 KPIs: open rate, send-day revenue, flow revenue | Weekly review |")
md.append("")
md.append("**Week 1 target:** £40–45k/day average (modest lift from cleanup + flow start). Big drag: tech-appliance kills happen Wed but old ones still ending mid-week.")
md.append("")

md.append("### WEEK 2 (May 13–19) — Premium prize anchor + VIP flow")
md.append("")
md.append("| Day | Owner | Action | KPI |")
md.append("|---|---|---|---|")
md.append("| **Wed May 13** | Joshua | Launch flagship: `2025 VOLKSWAGEN TIGUAN R-LINE` + `2021 ROLEX BLUESY` | New launches |")
md.append("| Wed May 13 | Aliyah | Activate VIP Tag flow + VIP Tier flow (both drafts) | Flows LIVE |")
md.append("| Wed May 13 | Aliyah | First VIP-only email send to D1 segment (top 5,898 customers) — exclusive £25 ticket-bundle | VIP campaign |")
md.append("| **Thu May 14** | Joshua | Launch `FAST FORD INSTANT WINS [£5K end]` — Friday draw | Launch |")
md.append("| Thu May 14 | Conrad/Alex | Pre-record TikTok Reels (vertical 9:16) for the Friday draw — first TikTok push | TikTok creative |")
md.append("| **Fri May 15** | All | 🔴 **2020 BMW M4 COMPETITION** flagship + Grand National themed instant wins | Target £60k |")
md.append("| Fri May 15 | Aliyah | First TikTok Spark Ad live (£100/day test, 5 creative variants) | TikTok live |")
md.append("| **Sat May 16** | Conrad/Devvy | Film: Winners content, prize-handover Reels for Insta+TikTok | 5 Reels |")
md.append("| **Sun May 17** | All | 🔴 `OLD-SCHOOL VAUXHALL INSTANT WINS [£5K end]` flagship + a £10k cash quick-draw | Target £55k |")
md.append("| **Mon May 18** | Aliyah | Activate Sunset Flow (email) + Sunset Flow (SMS) | Flows LIVE |")
md.append("| **Tue May 19** | Joshua | Review TikTok 4-day data — kill losers, scale winners 50% | TikTok optimisation |")
md.append("")
md.append("**Week 2 target:** £55–65k/day average. Premium anchor draws lift weekend ceiling.")
md.append("")

md.append("### WEEK 3 (May 20–26) — Scale winners + acquisition push")
md.append("")
md.append("| Day | Owner | Action | KPI |")
md.append("|---|---|---|---|")
md.append("| **Wed May 20** | Conrad | Meta ASC #1 launch (Lookalike-1% top-LTV) — £200/day for 7 days | Campaign live |")
md.append("| Wed May 20 | Joshua | Launch `2× HIGH PERFORMANCE INSTANT WINS` parallel formats (£5K end each) — staggered draw dates | 2 launches |")
md.append("| **Thu May 21** | Aliyah | Activate Abandoned Cart SMS leg (already-live email cart flow gets SMS) | Flow LIVE |")
md.append("| Thu May 21 | Conrad | Refresh top-3 Meta creative — new hooks, new prize photo angles | 3 new ads |")
md.append("| **Fri May 22** | All | 🔴 **Premium flagship car** (e.g. Range Rover SVR repeat / new Audi) | Target £75k |")
md.append("| Fri May 22 | Aliyah | Triple SMS day: 11:00 (heads-up), 17:00 (last chance), 19:30 (final hour) on engaged | SMS volume |")
md.append("| **Sat May 23** | Aliyah | 2nd reactivation drop — refined audience based on Week 1 results | Reactivation 2 |")
md.append("| **Sun May 24** | All | 🔴 `£100,000 TAX FREE CASH` event-style draw + 2× £5K instant wins | Target £80k |")
md.append("| **Mon May 25** | Conrad | Launch ASC #2 (engagement re-engagement audience) | Live |")
md.append("| **Tue May 26** | Aliyah | Mid-month VIP send + announce June flagship calendar | VIP touch |")
md.append("")
md.append("**Week 3 target:** £70–85k/day average. Big-prize Sunday targets first £80k+ day.")
md.append("")

md.append("### WEEK 4 (May 27 – June 2) — The £100k push")
md.append("")
md.append("| Day | Owner | Action | KPI |")
md.append("|---|---|---|---|")
md.append("| **Wed May 27** | Joshua | Launch 4 parallel `INSTANT WINS [£5K end]` formats — saturate the catalogue with proven winners | 4 launches |")
md.append("| Wed May 27 | Conrad | Scale Meta ASC #1 to £400/day if ROAS held; pause ASC #2 if <0.5× | Scale or kill |")
md.append("| **Thu May 28** | Aliyah | Activate any remaining drafted flows (Welcome SMS - Targeting & Retention) | All flows live |")
md.append("| **Fri May 29** | All | 🔴 **The £100k attempt** — TWO flagship cars (one £40k+ retail), £25k cash tonight, 3 instant-win formats finishing | **£100k target** |")
md.append("| Fri May 29 | Aliyah | Pre-Friday VIP send Wed 18:00; Thu 19:00 SMS first wave; Fri 09:00 + 17:00 email + 18:00 + 19:30 SMS | Saturation |")
md.append("| Fri May 29 | Karis/Conrad | Live broadcast 17:00–22:00 — extended edition w/ winner hand-over content | Live extended |")
md.append("| **Sat May 30** | Conrad/Alex | Recap content for Insta/TikTok — cement social proof | Content drop |")
md.append("| **Sun May 31** | All | 🔴 **Recovery flagship** — second £100k attempt with different prize mix | £100k target #2 |")
md.append("| **Mon June 1** | All | Review month: what worked, what didn't | Retro |")
md.append("| **Tue June 2** | Conrad/Aliyah | Lock June 4-week plan from learnings | Forward plan |")
md.append("")
md.append("**Week 4 target:** £85–100k/day average, ≥1 day at £100k+, with the floor raised above £45k/day.")
md.append("")

md.append("---")
md.append("")

# ============== 5. THE COMPETITIONS TO LAUNCH ==============
md.append("## 5. SPECIFIC COMPETITIONS TO LAUNCH (next 30 days)")
md.append("")
md.append("### 5.1 The 'GO LIVE' list — pull from your historical winners + new takes")
md.append("")
md.append("All formats below use the proven `[Draw {Day}]` + `£5,000 END PRIZE` template. Stagger so each week ends 6–8 of these.")
md.append("")
md.append("| # | Format | Why | Predicted £/day |")
md.append("|---|---|---|--:|")
md.append("| 1 | GOLD & WATCH INSTANT WINS [£5,000 END] | Top historical performer (£6,283/day) | £6,000 |")
md.append("| 2 | HIGH PERFORMANCE INSTANT WINS [£5,000 END] | Workhorse — multiple sub-themes (Audi/BMW/AMG) | £5,500 |")
md.append("| 3 | FAMILY CAR INSTANT WINS [£5,000 END] | Different audience demographic = incremental | £3,500 |")
md.append("| 4 | LUXURY SUV INSTANT WINS [£5,000 END] | High-AOV buyers | £4,500 |")
md.append("| 5 | FLAGSHIP DREAM CAR — Audi RSQ8 / BMW M4 / Range Rover SVR | Anchors Friday peak | £3,500 |")
md.append("| 6 | £50,000 TAX-FREE CASH (monthly anchor) | Recurring big-prize hook | £3,700 |")
md.append("| 7 | ROLEX WATCH INSTANT WINS [£5,000 END] | Watch buyers = high-value segment | £2,700 |")
md.append("| 8 | MX BIKE / SUR-RON INSTANT WINS [£5,000 END] | Bike audience (1,464 TikTok orders shows demand) | £2,600 |")
md.append("| 9 | £10,000 TAX-FREE CASH QUICK DRAW (weekly) | Mid-week quick convert | £900 |")
md.append("| 10 | FORD CONNECT / VAN INSTANT WINS | Trade audience — different demo | £2,700 |")
md.append("")

md.append("### 5.2 What's CURRENTLY upcoming — ranked predicted-revenue")
md.append("")
md.append("| Draw date | Day | Comp | Predicted total revenue | Action |")
md.append("|---|---|---|--:|---|")
preds_sorted = sorted(intel["upcoming_30day_draws"], key=lambda x:-x['expected_total_revenue'])
for p in preds_sorted:
    if p["expected_total_revenue"] >= 1000:
        flag = "🟢 PROMOTE"
        if p["predicted_rev_per_day"] > 2000: flag = "🔴 FLAGSHIP — heavy promo"
        md.append(f"| {p['draw_date']} | {p['draw_dow'][:3]} | {p['name'][:60]} | £{p['expected_total_revenue']:,.0f} | {flag} |")
    else:
        flag = "🟡 KILL or de-prioritise"
        md.append(f"| {p['draw_date']} | {p['draw_dow'][:3]} | {p['name'][:60]} | £{p['expected_total_revenue']:,.0f} | {flag} |")
md.append("")

md.append("---")
md.append("")

# ============== 6. META ADS DETAILED ==============
md.append("## 6. META ADS — what's broken and the exact fix")
md.append("")
md.append("### 6.1 Why Meta feels expensive (the diagnosis)")
md.append("")
md.append("Three things stack to make Meta look bad on the dashboard:")
md.append("")
md.append("1. **iOS 17 Mail Privacy Protection + ATT** — Apple drops 30–50% of pixel events. Without CAPI, Meta optimises against blind data.")
md.append("2. **Cross-device journeys collapse to 'direct'** — User clicks Meta ad on phone, comes back later on desktop direct = attribution credit goes to Direct/Typein in your data, but the order WAS caused by Meta. Your `direct/typein 57%` is the smoking gun.")
md.append("3. **Untagged ad URLs** — When the URL has no UTM, even when traffic does come through Meta, your WordPress order_attribution plugin can't credit it. So Meta is double-discredited.")
md.append("")
md.append("### 6.2 The 5-step fix (do all in Week 1)")
md.append("")
md.append("**Step 1 — Install Meta CAPI properly**")
md.append("- Use **PixelYourSite Pro** or **WP Pixel Cat** WordPress plugin — both have first-class CAPI for WooCommerce")
md.append("- In Events Manager → set Event Match Quality target ≥ 8.0/10")
md.append("- Send Purchase, AddToCart, ViewContent, InitiateCheckout, AddPaymentInfo events server-side")
md.append("- Verify: do a test purchase, check it shows up in Test Events with `match_keys=email,phone,client_ip` populated")
md.append("")
md.append("**Step 2 — UTMs on every Meta ad URL**")
md.append("- Use this Meta dynamic param block in every ad's destination URL:")
md.append("```")
md.append("?utm_source=facebook&utm_medium=paid&utm_campaign={{campaign.name}}&utm_content={{ad.name}}&utm_term={{adset.name}}&utm_id={{campaign.id}}")
md.append("```")
md.append("- Audit every active campaign by Friday — anything without UTMs gets paused until corrected.")
md.append("")
md.append("**Step 3 — Switch to Advantage+ Shopping Campaigns**")
md.append("- Build 2 Advantage+ Shopping Campaigns (ASC):")
md.append("  - **ASC #1 — Acquisition.** Audience: Broad UK 18+ (no interest targeting). Lookalike-1% built off your D1 customer email list (export the top 5,898 emails from CSV → upload as Custom Audience).")
md.append("  - **ASC #2 — Re-engagement.** Audience: People who interacted with FB/IG content in last 90d.")
md.append("- Budget: start at £100/day each, 4-day learning period, then scale 20% every 3 days while ROAS held.")
md.append("- Creative: 5–8 ads per campaign; rotate weekly.")
md.append("")
md.append("**Step 4 — Creative direction (mirror what's working in email)**")
md.append("Your top-performing email subject words: *Last, Chance, Cash, Car, £5,000, Wins, 50,000.* Your bottom-performing words: *Easter, Cashback, Promotion, Retargeting.*")
md.append("")
md.append("Apply to Meta:")
md.append("- ✅ DO: Hook on prize image (the actual car/watch/cash) + 'Last Chance' or 'Ends Tonight 20:00' + price anchor (£0.07 entry)")
md.append("- ✅ DO: 9:16 vertical for Stories/Reels; 1:1 square for feed")
md.append("- ✅ DO: UGC-style winner videos — your strongest social proof")
md.append("- ❌ AVOID: Generic 'promotion' / 'cashback' framing")
md.append("- ❌ AVOID: Static product shots without prize size context")
md.append("")
md.append("**Step 5 — Pause discipline**")
md.append("- Every Friday 18:00, pause any ad set that ran 7+ days at <0.5× CAPI-measured ROAS")
md.append("- Keep ad set count ≤ 8 active — Meta's algorithm needs ≥50 conversions/week per ad set to optimise")
md.append("")

md.append("### 6.3 Audience uploads (Custom Audiences to build today)")
md.append("")
md.append("| Audience name | Source data | Size | Use |")
md.append("|---|---|--:|---|")
md.append("| `NC_VIP_D1` | Top LTV decile from `orders_3mo.csv` | 5,898 | Lookalike seed |")
md.append("| `NC_BUYERS_90D` | All unique emails from `orders_3mo.csv` | 58,985 | Exclusion list (don't ad-spend on existing recent buyers) |")
md.append("| `NC_DORMANT_PAYING` | Customer DB minus 90d-buyers | ~349,000 | Reactivation campaign audience |")
md.append("| `NC_HIGH_INTENT_CASH` | Klaviyo segment via export | varies | Lookalike for 'Cash' creatives |")
md.append("| `NC_HIGH_INTENT_CARS` | Klaviyo segment via export | varies | Lookalike for car creatives |")
md.append("")
md.append("### 6.4 Meta budget floor (the 'do not go below this' line)")
md.append("")
md.append("Once CAPI shows you the true ROAS, Meta is profitable enough to fund itself. Until then:")
md.append("- **Floor:** £200/day total Meta spend during Week 1 (don't kill the channel)")
md.append("- **Week 2:** £400/day if CAPI ROAS ≥ 2.5×")
md.append("- **Week 3:** £800/day if held")
md.append("- **Week 4:** £1,500/day if held — this is the volume needed for £100k/day target")
md.append("- **Cap:** Never spend more than 12% of revenue on Meta (your AOV is too low for higher % to work)")
md.append("")

md.append("---")
md.append("")

# ============== 7. EMAIL + SMS SCHEDULE ==============
md.append("## 7. EMAIL + SMS SEND SCHEDULE — every send for 4 weeks")
md.append("")
md.append("Anchored to 17:00–18:00 UTC (highest revenue per recipient) and Friday/Sunday peak days.")
md.append("")
md.append("**Daily standing schedule (Monday → Sunday)**")
md.append("")
md.append("| Day | Time UTC | Channel | Audience | Purpose |")
md.append("|---|---|---|---|---|")
md.append("| Mon | 17:00 | Email | Engaged 90d + Placed Order 90d | Mon kick-off / new draws |")
md.append("| Mon | 18:00 | SMS | High Intent Cash | Mon urgency |")
md.append("| Tue | 17:00 | Email | High Intent Car/Bike | Mid-week last chance |")
md.append("| Tue | 18:00 | SMS | Purchased 30d | Loyal-buyer push |")
md.append("| Wed | 17:00 | Email | Newsletter (broad) | Mid-week build-up |")
md.append("| Wed | 18:00 | SMS | High Intent Cash | Push |")
md.append("| Thu | 17:00 | Email | Engaged 60d - Cash Players | Last-chance Thu |")
md.append("| Thu | 18:00 | SMS | Purchased 30d | Loyalty |")
md.append("| **Fri** | **09:00** | **Email** | Engaged 60d | 🔴 **Ends Today flagship #1** |")
md.append("| **Fri** | **17:00** | **Email** | High-Intent Cash + Car/Bike + High-Spenders | 🔴 **Ends Tonight flagship #2** |")
md.append("| **Fri** | **18:00** | **SMS** | High Intent Car/Bike | 🔴 **Tonight 20:00** |")
md.append("| **Fri** | **19:30** | **SMS** | Purchased 90d (1 hr to draw) | 🔴 **Final hour** |")
md.append("| Sat | 11:00 | Email | Dormant DB (reactivation week 1) | Reactivation #1 |")
md.append("| Sat | 17:00 | Email | New Subscribers 30d | Welcome / re-engage |")
md.append("| **Sun** | **09:00** | **Email** | Engaged + Cash | 🔴 **Sunday Ends Today** |")
md.append("| **Sun** | **17:00** | **Email** | High Spenders + Retargeting | 🔴 **Sunday Ends Tonight** |")
md.append("| **Sun** | **18:00** | **SMS** | High Intent Cash | 🔴 **Tonight 20:00** |")
md.append("")
md.append("**Total weekly sends: 12 email + 6 SMS = 18 scheduled touches.**")
md.append("")
md.append("### 7.1 Subject-line cheatsheet (built from your top campaigns)")
md.append("")
md.append("**WINNING formula:**")
md.append("`[Day] - [Date] - Last Chance - [Theme] - [Prize Hook]`")
md.append("")
md.append("Examples that won:")
md.append("- `Tuesday - 31st March 2026 - Last Chance - Cash - Cash Beast Instants` (£12,976)")
md.append("- `Monday - 9th February 2025 - Cars & Bikes - High Performance` (£12,292)")
md.append("- `Thursday - 26th February 2026 - Ends Tomorrow - Renault Race Truck` (£10,964)")
md.append("")
md.append("**Word frequency in winners vs losers (90d data):**")
md.append("")
winning = intel.get("winning_subject_words", [])[:12]
losing = intel.get("losing_subject_words", [])[:12]
md.append("| Winning words (use more) | Lift | | Losing words (use less / never) | Lift |")
md.append("|---|--:|---|---|--:|")
for i in range(max(len(winning), len(losing))):
    w = winning[i] if i < len(winning) else ("","")
    l = losing[i] if i < len(losing) else ("","")
    md.append(f"| {w[0]} | +{w[1]} | | {l[0]} | {l[1]} |")
md.append("")
md.append("**Avoid these words:** *Easter, Cashback, Promotion, Retargeting* (and any words tagged 2025 — buyers respond to current year framing).")
md.append("")

md.append("---")
md.append("")

# ============== 8. STAFF REPORTING ==============
md.append("## 8. STAFF REPORTING STRUCTURE")
md.append("")
md.append("### 8.1 Reporting lines")
md.append("")
md.append("```")
md.append("                          OWNER / CEO")
md.append("                               │")
md.append("       ┌──────────┬────────────┼───────────┬─────────────┐")
md.append("       │          │            │           │             │")
md.append("    Conrad      Aliyah      Joshua      Karis       Logistics")
md.append("   (Creative)   (Admin/    (Web Ops/  (Presenter)   (Cory/Colin/")
md.append("                Marketing)  Comp Setup)              Devvy/Matt Jr)")
md.append("       │          │            │           │             │")
md.append("    Alex S.    (no reports)  (no reports) (no reports) (Matt Jr ↔")
md.append("    Devvy on                                            Conrad ↔")
md.append("    shoot                                               Joshua)")
md.append("    days                                                ")
md.append("    Karis on                                             ")
md.append("    pre-record")
md.append("```")
md.append("")
md.append("### 8.2 Reporting cadence")
md.append("")
md.append("| Frequency | Meeting | Owner | Attendees | Output |")
md.append("|---|---|---|---|---|")
md.append("| Daily 09:00 (15 min stand-up) | Today's draw + send schedule | Aliyah | All on-site | Send list locked / draw checklist |")
md.append("| Daily 21:30 (10 min) | Live-draw debrief | Karis | Karis, Joshua, Alex, Conrad | Issues log |")
md.append("| Mon 10:00 (45 min) | Weekly KPI review | Conrad | Conrad, Aliyah, Joshua | KPI scorecard, week's send schedule |")
md.append("| Fri 14:00 (30 min) | Pre-flagship readiness | Joshua | All | Friday checklist signed off |")
md.append("| Last Tue of month (60 min) | Monthly retro | Conrad | Senior team | Wins/misses, next month's flagship calendar |")
md.append("")

md.append("### 8.3 What each person reports daily")
md.append("")
md.append("| Person | Reports to | Daily output | KPI |")
md.append("|---|---|---|---|")
md.append("| **Conrad** | Owner | Production schedule, Meta status, agency notes | 5 new creatives/week |")
md.append("| **Alex** | Conrad | Edits/films delivered | 1 daily Reel + 1 weekly long-form |")
md.append("| **Joshua** | Owner | Live-comp count, kill list executed, web fixes | 587 → ≤500 cleanup by W2 |")
md.append("| **Aliyah** | Owner | Today's send report (sends, opens, clicks, revenue) | 18 weekly scheduled sends 100% executed |")
md.append("| **Karis** | Owner (creative dotted to Conrad) | Live audience peak count, sales lift during live | Avg 800+ concurrent on Fri/Sun |")
md.append("| **Kyrell** | Joshua | Winners contacted, stock runs done, vehicle status | Same-day winner contact 100% |")
md.append("| **Matt Jr** | Joshua | Unit cleanliness, vehicle prep, stage setup | Stage ready 16:00 daily |")
md.append("| **Cory** | Kyrell | Daily run sheet | All collections same-day |")
md.append("| **Colin** | Joshua | Long-haul prize delivery confirmation | 100% on-time |")
md.append("| **Devvy** | Conrad | Prize-reveal content delivered | 6 reveals/week |")
md.append("")

md.append("---")
md.append("")

# ============== 9. KPI DASHBOARD ==============
md.append("## 9. KPI DASHBOARD — what to watch every day")
md.append("")
md.append("### 9.1 Daily KPIs (post in shared dashboard / Slack 09:00)")
md.append("")
md.append("| KPI | Source | Yesterday | 7-day avg | Target |")
md.append("|---|---|---|---|---|")
md.append("| Daily revenue | WooCommerce | — | — | £80k+ (Wk4) |")
md.append("| Orders | WooCommerce | — | — | 8,000+ |")
md.append("| New customers | WooCommerce | — | — | 1,800+ |")
md.append("| AOV | WooCommerce | — | — | £12+ |")
md.append("| Email open rate | Klaviyo | — | — | 45%+ |")
md.append("| Email rev/recipient | Klaviyo | — | — | £0.25+ |")
md.append("| SMS click rate | Klaviyo | — | — | 25%+ |")
md.append("| SMS rev/send | Klaviyo | — | — | £0.20+ |")
md.append("| SMS estimated cost | Klaviyo × £0.04 | — | — | <£1,500/day |")
md.append("| Live concurrent peak (Fri/Sun) | YouTube Studio | — | — | 1,000+ |")
md.append("| Trustpilot reviews this week | Trustpilot | — | — | 50+ |")
md.append("| Meta CAPI ROAS (7d) | Meta Events Mgr | — | — | 2.5×+ |")
md.append("| Meta spend | Meta Ads Mgr | — | — | £400–1,500/day |")
md.append("| TikTok ad ROAS | TikTok Ads Mgr | — | — | 1.5×+ |")
md.append("")

md.append("### 9.2 Weekly KPIs (Monday 09:00 review)")
md.append("")
md.append("| KPI | Last week | Target |")
md.append("|---|--:|--:|")
md.append("| Total revenue | — | £700k (W4) |")
md.append("| Flagship Friday revenue | — | £100k |")
md.append("| Flagship Sunday revenue | — | £80k |")
md.append("| Reactivation campaign rev | — | £15k+ each |")
md.append("| New flows triggered | — | 4–6 in W1, 8 in W2, 10 in W3 |")
md.append("| Comps killed | — | 88 by end of W2 |")
md.append("| New flagship comps launched | — | 3 cars / week |")
md.append("| TikTok creative tests | — | 5 weekly |")
md.append("| Meta creative refresh | — | 3 weekly |")
md.append("")

md.append("---")
md.append("")

# ============== 10. RISK REGISTER ==============
md.append("## 10. RISK REGISTER")
md.append("")
md.append("| Risk | Probability | Impact | Mitigation |")
md.append("|---|---|---|---|")
md.append("| Meta CAPI install delays | Medium | High | Use PixelYourSite Pro (1-day install) — fallback to manual server-side via PHP |")
md.append("| Tech-appliance kills cause refunds | Low | Medium | Run them out (let existing draw dates complete) — don't pull live mid-comp |")
md.append("| Reactivation send hits spam folder | Medium | High | Aliyah warms the IP first with smaller sends (5k/day for 3 days) |")
md.append("| Friday flagship car doesn't sell out | Medium | High | Pre-commit: any car ≥£40k retail must have 30+ days of pre-promotion. Track ticket-velocity vs target curve daily — kill or convert to instant-win if behind by 20% at day 7 |")
md.append("| Karis or Kyrell unavailable for live | Medium | Critical | Cross-train Joshua + Aliyah as backup presenters |")
md.append("| TikTok ads compliance rejection | High (lottery/comp space) | Medium | Test with promotional creative first (no 'win' language); use Spark Ads off organic posts where possible |")
md.append("| Meta account flagged for raffle/competition policy | Medium | Critical | Use 'prize draw' / 'instant win' language not 'lottery'; ensure terms are clearly displayed; have backup ad account warmed up |")
md.append("| Klaviyo deliverability drops | Low | High | Keep unsub <0.2%, run sunset flow, never send full-DB blast more than monthly |")
md.append("| Live unit power/internet failure | Medium | Critical | Backup 4G hotspot; backup laptop pre-loaded; mobile-phone livestream fallback |")
md.append("| Refund / cancellation rate creeps up | Medium | High | Currently 6.3% all-time. Watch 7-day rolling — alert at 8%. Driver: clearer T&Cs, better answer-question UX |")
md.append("")

md.append("---")
md.append("")

# ============== 11. DAILY CADENCE ==============
md.append("## 11. THE DAILY CADENCE — what every day looks like")
md.append("")
md.append("### Standard non-flagship day (Mon/Tue/Wed/Thu/Sat)")
md.append("")
md.append("| Time UTC | Action | Owner |")
md.append("|---|---|---|")
md.append("| 07:00 | Matt Jr opens unit, starts cleaning + vehicle prep | Matt Jr |")
md.append("| 08:00 | Conrad finishes overnight edits / draw-day pics | Conrad |")
md.append("| 08:00 | Kyrell results + instant-win uploads | Kyrell |")
md.append("| 09:00 | **Daily stand-up** — today's sends, today's draw, blockers | Aliyah leads |")
md.append("| 09:00 | Joshua web ops — comp prep, draft-to-live | Joshua |")
md.append("| 09:00 | Aliyah inbox + Trustpilot + winner posts | Aliyah |")
md.append("| 10:00 | Filming slot (Tue/Thu) or ideation/scripts (Mon/Wed) | Conrad + Alex + Karis |")
md.append("| 13:00 | Editing (Conrad/Alex), site fixes (Joshua), van runs (Kyrell), social pushes (Aliyah) | Various |")
md.append("| 16:30 | **17:00 send scheduled in Klaviyo** (lock by 16:30) | Aliyah |")
md.append("| 17:00 | Email + SMS land. Build-up Reels begin live. | Aliyah / Karis |")
md.append("| 18:00 | Karis goes live — pre-draw build-up | Karis |")
md.append("| 19:30 | Final-hour SMS (high-intent only) | Aliyah |")
md.append("| 20:00 | **LIVE DRAW** — Karis presenting, Joshua co, Alex camera | Live team |")
md.append("| 21:00 | Pack down + post-draw social wrap | Live team + Aliyah |")
md.append("| 21:30 | **Live-draw debrief** — issues log | Karis leads |")
md.append("")

md.append("### Flagship day (Fri/Sun)")
md.append("")
md.append("| Time UTC | Action | Owner |")
md.append("|---|---|---|")
md.append("| 07:00 | Matt Jr deep-clean unit + stage cabling | Matt Jr |")
md.append("| 08:00 | Conrad creates draw-day pics, schedules to FB + YT | Conrad |")
md.append("| 08:00 | Colin starts long-haul prize delivery | Colin (Mon/Wed/Fri) |")
md.append("| **09:00** | **'Ends Today' email send** to Engaged 60d | Aliyah |")
md.append("| 09:00 | Daily stand-up — flagship readiness | Conrad leads |")
md.append("| 11:00 | Reactivation send (Sat) or Friday teaser SMS | Aliyah |")
md.append("| 13:00 | Filming/edits + final stage check | Conrad |")
md.append("| 14:00 | Devvy arrives — prize-reveal shoot prep | Devvy |")
md.append("| 16:00 | Karis arrives, hair/make-up, pre-record build-up | Karis |")
md.append("| 16:30 | **Lock 17:00 sends in Klaviyo (Email + SMS)** | Aliyah |")
md.append("| **17:00** | **Email + SMS land** — 'Ends Tonight' | Aliyah |")
md.append("| 17:00 | Karis live build-up Reels | Karis |")
md.append("| **18:00** | **SMS final wave 'Tonight 20:00'** | Aliyah |")
md.append("| 18:00 | Karis goes full live | Karis |")
md.append("| 19:30 | **Final-hour SMS** (highest-intent only — Engaged 30d + cart abandoners) | Aliyah |")
md.append("| **20:00** | 🔴 **LIVE DRAW** — Conrad directing, Devvy on-camera prize reveal | All |")
md.append("| 21:00 | Pack down + winner content | Karis + Devvy |")
md.append("| 22:00 | Wrap | All |")
md.append("")

md.append("---")
md.append("")

# ============== 12. THE £100K DAY PLAYBOOK ==============
md.append("## 12. THE £100K DAY PLAYBOOK")
md.append("")
md.append("To execute a £100k Friday, you need everything below in place:")
md.append("")
md.append("### 12.1 Prize stack (lined up 7 days before)")
md.append("")
md.append("- 1× **flagship car** £40k+ retail (Audi RSQ8 / BMW M4 / Range Rover SVR / Porsche tier)")
md.append("- 1× **£25k tax-free cash quick-draw**")
md.append("- 3× **£5,000-end-prize instant-win formats** (gold/watch + cars + cash)")
md.append("- 1× **£10k Friday-only flash entry** at 19:00 (5,000 tickets, sub-£1 each — high velocity)")
md.append("- 1× **bundle deal** (£25 ticket = entries to all 5 = high AOV mechanic)")
md.append("")
md.append("### 12.2 Send choreography (Thu → Fri)")
md.append("")
md.append("- **Thu 17:00** Email — Build-up: 'Friday's £40k car ends tomorrow' to Engaged 60d (~30k recipients)")
md.append("- **Thu 19:00** SMS — `High Intent Car/Bike` segment — 'Friday's flagship'")
md.append("- **Fri 09:00** Email — 'Ends Today' to Engaged 60d (~30k)")
md.append("- **Fri 11:00** Email — Reactivation send to dormant DB if Saturday slot already used (~50k)")
md.append("- **Fri 17:00** Email × 2 — `High-Intent Cash` + `High-Spenders` separately, customised subject (~50k each)")
md.append("- **Fri 18:00** SMS — `High Intent Car/Bike` (~25k)")
md.append("- **Fri 19:00** SMS — `Cart Abandoners last 24h` (~5k, highest-intent)")
md.append("- **Fri 19:30** SMS — `Purchased 30d` final hour push (~15k)")
md.append("")
md.append("### 12.3 Paid-media support")
md.append("")
md.append("- **Mon–Wed:** Build awareness — flagship car teaser ads on Meta + TikTok")
md.append("- **Thu–Fri:** Conversion mode — 'Ends tonight' ads to all warm audiences (cart abandoners, 30d engaged, 90d engaged)")
md.append("- **Fri £-spend distribution:** 60% Meta, 25% TikTok, 15% Google brand search")
md.append("")
md.append("### 12.4 Live-draw conversion mechanics")
md.append("")
md.append("- Karis announces 'final 1,000 tickets' urgency hook every 15 min from 19:00")
md.append("- Joshua pinned-comment in chat: 'Last chance to enter, draw begins 20:00 sharp'")
md.append("- Aliyah real-time monitors sales — if a comp is undersold, Karis gives extra promo time")
md.append("- Pre-recorded winner reveal Reel from previous Friday plays at 19:55 to anchor social proof")
md.append("- Live continues 20:00–22:00 with prize hand-over content")
md.append("")
md.append("### 12.5 The £100k day math")
md.append("")
md.append("Achievable revenue mix on a flagship Friday:")
md.append("")
md.append("| Source | Expected revenue |")
md.append("|---|--:|")
md.append("| Flagship car finale | £25,000 |")
md.append("| £25k cash quick-draw | £18,000 |")
md.append("| Instant-win format #1 (gold/watch) | £15,000 |")
md.append("| Instant-win format #2 (high-perf) | £15,000 |")
md.append("| Instant-win format #3 (family/SUV) | £10,000 |")
md.append("| £10k flash entry | £8,000 |")
md.append("| Bundle deal upsell | £5,000 |")
md.append("| Other live comps tail | £4,000 |")
md.append("| **TOTAL** | **£100,000** |")
md.append("")

md.append("---")
md.append("")

# ============== 13. ADDRESSING WHAT NEEDS ADDRESSING ==============
md.append("## 13. THE FULL 'WHAT NEEDS ADDRESSING' LIST")
md.append("")
md.append("Bullet-listed in priority order for the next 14 days:")
md.append("")
md.append("**🔴 CRITICAL — do this week**")
md.append("- [ ] Install Meta CAPI via PixelYourSite Pro / WP Pixel Cat (Conrad + agency)")
md.append("- [ ] Add UTMs to every Meta + TikTok + Google ad URL (Joshua audit)")
md.append("- [ ] Activate Welcome Series Email flow from draft (Aliyah)")
md.append("- [ ] Activate First Purchase Incentive flow (Aliyah)")
md.append("- [ ] Activate Winback Flow (Aliyah)")
md.append("- [ ] Drop the 13 currently-live tech-appliance comps from promotion (let existing draws run, no new ones) (Joshua)")
md.append("- [ ] Build Custom Audience NC_VIP_D1 from D1 customer emails (Conrad → Meta)")
md.append("- [ ] Build NC_BUYERS_90D exclusion audience (Conrad → Meta)")
md.append("- [ ] Schedule Saturday reactivation campaign to dormant DB (Aliyah)")
md.append("")
md.append("**🟠 IMPORTANT — do next week**")
md.append("- [ ] Activate VIP Tag flow + VIP Tier flow (Aliyah)")
md.append("- [ ] Activate Sunset Flow Email + SMS (Aliyah)")
md.append("- [ ] Launch Meta ASC #1 — Lookalike-1% top-LTV (Conrad)")
md.append("- [ ] Launch Meta ASC #2 — Engagement re-engagement (Conrad)")
md.append("- [ ] First TikTok Spark Ad live (£100/day test, 5 creatives) (Conrad/Alex)")
md.append("- [ ] Implement weekly Friday creative refresh on Meta (Conrad)")
md.append("- [ ] Implement Klaviyo deliverability check (open >40%, unsub <0.2%, spam <0.05%) (Aliyah)")
md.append("")
md.append("**🟡 Process / structural**")
md.append("- [ ] Single source of truth for comps — Joshua owns the master CMS doc (resolves Conrad's flagged blocker)")
md.append("- [ ] Move Conrad to hard 17:00 stop Mon–Thu (frees senior creative time)")
md.append("- [ ] Move Karis to 16:00 start (build-up Reels capture)")
md.append("- [ ] Onboard Matt Jr as floor/cabling/setup owner (frees other staff from cleaning)")
md.append("- [ ] Cross-train Joshua + Aliyah as backup presenter")
md.append("- [ ] Stand up Slack/Teams channel `#daily-stats` for the 09:00 KPI post")
md.append("- [ ] Build live-streamed shared dashboard (Looker Studio / Klaviyo + Wc + Meta) for the daily KPIs in §9")
md.append("- [ ] Document refund/cancellation flow — current 6.3% lifetime cancel rate needs tightening")
md.append("- [ ] Trustpilot push — Aliyah's mornings now drive review velocity (target 50+/week)")
md.append("")
md.append("**🟢 Growth — month 2 onwards**")
md.append("- [ ] TikTok Shop integration (your 1,464 TikTok orders show demand; Shop converts at 2–3× normal social)")
md.append("- [ ] Apple Search Ads if ever building an app")
md.append("- [ ] Loyalty / tier programme (e.g. Bronze/Silver/Gold based on 90-day spend)")
md.append("- [ ] Refer-a-friend mechanic (1 free entry for every referred buyer)")
md.append("- [ ] Postcard mailer to top D1 customers monthly (your 5,898 VIPs deserve physical touch)")
md.append("- [ ] Win-rate transparency dashboard for users (builds trust, increases retention)")
md.append("")

md.append("---")
md.append("")
md.append("## 14. WHERE THE DATA CAME FROM")
md.append("")
md.append("Every number in this report was pulled live via API:")
md.append("- **WooCommerce REST API** — 299,858 orders + 587 live products + 442,229 customer count (`/wp-json/wc/v3/orders`, `/products`, `/customers`, `/reports`)")
md.append("- **Klaviyo API** — 127 email + 94 SMS campaigns, performance metrics, 32 flows, 8 lists with profile counts, 180 segments")
md.append("- **All raw data** preserved in `/raw` (90 daily JSON files), `/klaviyo` (10 JSON exports), `competitions.csv`, `orders_3mo.csv`, `deep_intel.json`")
md.append("")
md.append("### Files in this audit pack")
md.append("")
md.append("| File | Purpose |")
md.append("|---|---|")
md.append("| `100K_BLUEPRINT.md` / `.html` | This document — the master plan |")
md.append("| `MASTER_AUDIT.md` / `.html` | Combined sales + email/SMS + competitions + rota |")
md.append("| `STAFF_ROTA.md` / `.html` | Standalone staff schedule |")
md.append("| `AUDIT_REPORT.md` / `.html` | Original WooCommerce-only audit |")
md.append("| `COMPETITIONS_REPORT.md` | Per-competition deep-dive |")
md.append("| `orders_3mo.csv` | 138 MB — every order with all attribution metadata |")
md.append("| `competitions.csv` | 522 unique competitions with revenue/orders/buyers/dates |")
md.append("| `new_customers.csv` | Daily new-customer signups (deduped) |")
md.append("| `channels.csv` / `daily.csv` / `hourly.csv` / `monthly_pattern.csv` / `email_send_times.csv` | Pivots |")
md.append("| `deep_intel.json` | Combined intelligence pack used to build this blueprint |")
md.append("| `klaviyo/*.json` | Raw Klaviyo data — campaigns, metrics, flows, lists, segments |")
md.append("| `raw/*.json` | 90 days of raw WooCommerce orders |")
md.append("")
md.append("**End of blueprint. Execute in week 1, measure in week 2, scale in week 3, hit £100k in week 4.**")
md.append("")

md_text = "\n".join(md)
with open(OUT_MD, "w") as f:
    f.write(md_text)
print(f"Wrote {OUT_MD}")

# HTML
import markdown
html_body = markdown.markdown(md_text, extensions=["tables","fenced_code"])
html = f"""<!doctype html><html><head><meta charset=utf-8>
<title>Nitrous £100k Day Blueprint</title>
<style>
body{{font-family:-apple-system,Segoe UI,Roboto,sans-serif;max-width:1400px;margin:30px auto;padding:0 24px;color:#0f172a;line-height:1.6}}
h1{{color:#0b1220;border-bottom:4px solid #dc2626;padding-bottom:10px;font-size:32px}}
h2{{color:#7c1d1d;margin-top:38px;border-bottom:2px solid #fee2e2;padding-bottom:6px}}
h3{{color:#991b1b;margin-top:22px}}
h4{{color:#b91c1c}}
table{{border-collapse:collapse;width:100%;margin:14px 0;font-size:13px}}
th,td{{padding:7px 9px;border:1px solid #e5e7eb;vertical-align:top}}
th{{background:#fef2f2;color:#7c1d1d;font-weight:600;text-align:left}}
tr:nth-child(even){{background:#fafbff}}
code{{background:#fef3c7;padding:1px 5px;border-radius:3px;font-size:0.9em}}
pre{{background:#0b1220;color:#e2e8f0;padding:14px;border-radius:6px;overflow:auto}}
strong{{color:#0b1220}}
ul li, ol li{{margin:5px 0}}
hr{{border:none;border-top:2px solid #e5e7eb;margin:28px 0}}
</style></head><body>{html_body}</body></html>"""
with open(f"{ROOT}/100K_BLUEPRINT.html","w") as f: f.write(html)
print(f"Wrote {ROOT}/100K_BLUEPRINT.html")
