#!/usr/bin/env python3
"""
Fix Scripts + Schedule tab schemas and add Client Profile tabs for all 3 client sheets.
Schemas were wrong — content-calendar.html reads 'Script' not 'Hook', and
Schedule needs Title/Week/Day/Platforms not Date/Platform/Caption/Status/Link.
"""
import json, requests, time
from pathlib import Path

TOKEN_FILE = Path.home() / ".config/google-workspace-mcp/profiles/emerson-north/tokens.json"
CREDS_FILE = Path.home() / ".config/google-workspace-mcp/profiles/emerson-north/credentials.json"

def get_token():
    tokens = json.loads(TOKEN_FILE.read_text())
    if tokens.get("expiry_date", 0) / 1000 > time.time() + 60:
        return tokens["access_token"]
    creds = json.loads(CREDS_FILE.read_text())
    web = creds.get("web") or creds.get("installed", {})
    r = requests.post("https://oauth2.googleapis.com/token", data={
        "client_id": web["client_id"], "client_secret": web["client_secret"],
        "refresh_token": tokens["refresh_token"], "grant_type": "refresh_token",
    })
    r.raise_for_status()
    new = r.json()
    tokens["access_token"] = new["access_token"]
    tokens["expiry_date"] = int((time.time() + new["expires_in"]) * 1000)
    TOKEN_FILE.write_text(json.dumps(tokens, indent=2))
    return tokens["access_token"]

def add_tab(token, sheet_id, name):
    r = requests.post(
        f"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}:batchUpdate",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"requests": [{"addSheet": {"properties": {"title": name}}}]}
    )
    if r.ok:
        print(f"  + Created tab: {name}")
    elif "already exists" in r.text:
        print(f"  ~ Tab exists: {name}")
    else:
        print(f"  ! Tab error {r.status_code}: {r.text[:100]}")
    return r.ok or "already exists" in r.text

def write_tab(token, sheet_id, tab, data):
    rows = len(data)
    cols = max(len(row) for row in data)
    end_col = chr(ord('A') + cols - 1)
    rng = requests.utils.quote(f"{tab}!A1:{end_col}{rows}")
    r = requests.put(
        f"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/{rng}?valueInputOption=RAW",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"values": data, "majorDimension": "ROWS"}
    )
    if r.ok:
        print(f"  ✓ {tab}: {rows} rows")
    else:
        print(f"  ✗ {tab}: {r.status_code} {r.text[:100]}")

def get_tabs(token, sheet_id):
    r = requests.get(
        f"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}",
        headers={"Authorization": f"Bearer {token}"}
    )
    return [s["properties"]["title"] for s in r.json().get("sheets", [])] if r.ok else []


# ── Column schemas ─────────────────────────────────────────────────────────────
SCRIPTS_HEADER = ["Title", "Type", "Hook", "Script", "CTA", "Status", "Platform", "Week", "Day", "Campaign", "Trending", "Notes", "Images"]
SCHEDULE_HEADER = ["Title", "Week", "Day", "Platforms"]
PROFILE_HEADER = ["Key", "Value"]

# ── NC data ────────────────────────────────────────────────────────────────────
NC_SCRIPTS = [SCRIPTS_HEADER] + [
    ["ADHD in the ER — What I See Every Shift", "Video",
     "What nurses see that doctors miss every single day...",
     "[HOOK]\nWhat nurses see that doctors miss every single day...\n\n[BODY]\nI've been an ER nurse for 8 years. And in that time, I've seen one thing that doctors consistently overlook — especially with ADHD patients. When someone comes in acting 'difficult,' asking too many questions, or can't sit still — most staff label them as noncompliant. But what I see is an undiagnosed or undertreated ADHD patient who needs a completely different approach. Here's what I do differently, and what it means for their outcome.\n\n[CTA]\nIf you're a nurse who wants to build a brand from your expertise, my Healthcare Creator Starter Kit is free. Link in bio.",
     "Healthcare Creator Starter Kit — free. Link in bio.", "scheduled", "tiktok,ig", "1", "Tue", "Healthcare Creator Starter Kit", "ADHD awareness", "Ready to film", ""],
    ["Hookah Myths Debunked", "Video",
     "Everything you think you know about hookah is wrong.",
     "[HOOK]\nEverything you think you know about hookah is wrong.\n\n[BODY]\nI hear it every week in the ER. 'But hookah is safer than cigarettes, right?' Let me break down the 3 biggest hookah myths I hear from patients — and what the research actually shows. This is not an opinion. This is what the data says.\n\n[CTA]\nFollow for more healthcare truths you won't hear anywhere else.",
     "Follow for more truth nobody tells you.", "scheduled", "tiktok", "1", "Wed", "Healthcare Creator Starter Kit", "Health myths debunked", "Ready to film", ""],
    ["Chronic Stress — What the ER Taught Me", "Video",
     "I've worked with patients who had no idea they were dying.",
     "[HOOK]\nI've worked with patients who had no idea they were dying from stress.\n\n[BODY]\nChronic stress doesn't announce itself. It shows up as a 'random' heart attack at 38. A stroke at 42. Blood pressure nobody caught because it felt normal. I've seen it too many times. Here are the 4 signs your body is already in red alert — and what to do about it before it's too late.\n\n[CTA]\nShare this with someone who needs to hear it.",
     "Share this with someone who needs to hear it.", "scheduled", "tiktok,ig", "1", "Thu", "Healthcare Creator Starter Kit", "Chronic illness", "Ready to film", ""],
    ["Sleep Hygiene for Night Shift Workers", "Video",
     "Night shift nurses age faster — here's the science.",
     "[HOOK]\nNight shift nurses age faster — and I have the research to prove it.\n\n[BODY]\nYour body runs on a circadian clock that evolution built over 200,000 years. Night shift breaks that clock every single shift. Here's what's actually happening to your body when you work nights — and the 3 specific things I do to slow the damage.\n\n[CTA]\nSave this for after your next shift.",
     "Save this for after your next shift.", "draft", "tiktok", "1", "Fri", "Healthcare Creator Starter Kit", "Night shift life", "Ready to film", ""],
    ["ADHD & Black Men — The Misdiagnosis Crisis", "Video",
     "Black men with ADHD are being failed by the healthcare system.",
     "[HOOK]\nBlack men with ADHD are being failed by the healthcare system. I see it every shift.\n\n[BODY]\nADHD in Black men gets misdiagnosed as conduct disorder, oppositional defiance, or 'attitude' at alarming rates. I've been in the ER when it happens. The patient acts out, nobody asks why, and they leave without help. I'm breaking this down because nobody else in healthcare is talking about it plainly.\n\n[CTA]\nDrop a 1 if you or someone you know has experienced this.",
     "Drop a 1 if this hit close to home.", "draft", "tiktok,ig", "2", "Mon", "Healthcare Creator Starter Kit", "Racial health disparities", "Ready to film", ""],
    ["TikTok Live Framework for Nurse Creators", "Video",
     "Most nurse creators go live and waste it. Here's what actually works.",
     "[HOOK]\nMost nurse creators go live and waste the whole opportunity. Here's the framework that changed everything.\n\n[BODY]\nGoing live isn't just pressing a button. There's a structure that keeps people watching, builds authority, and converts viewers into followers. I tested 12 different live formats over 6 months. This is the one that works for healthcare creators specifically.\n\n[CTA]\nHealthcare Creator Starter Kit — free in bio. Includes my full live framework.",
     "Get the full framework free — Healthcare Creator Starter Kit, link in bio.", "draft", "tiktok,ig", "2", "Tue", "Healthcare Creator Starter Kit", "Creator strategy", "Ready to film", ""],
]

NC_SCHEDULE = [SCHEDULE_HEADER] + [
    ["ADHD in the ER — What I See Every Shift", "1", "Tue", "tiktok,ig"],
    ["Hookah Myths Debunked", "1", "Wed", "tiktok"],
    ["Chronic Stress — What the ER Taught Me", "1", "Thu", "tiktok,ig"],
    ["Sleep Hygiene for Night Shift Workers", "1", "Fri", "tiktok"],
    ["ADHD & Black Men — The Misdiagnosis Crisis", "2", "Mon", "tiktok,ig"],
    ["TikTok Live Framework for Nurse Creators", "2", "Tue", "tiktok,ig"],
]

NC_PROFILE = [PROFILE_HEADER] + [
    ["client_name", "Nurse Charles"],
    ["full_name", "Charles Folsom"],
    ["niche", "Healthcare Education & Nursing Content"],
    ["target_audience", "Nurses, healthcare workers, health-conscious general public interested in real talk about healthcare"],
    ["tone", "Authoritative but approachable — real talk from a nurse's perspective. Educational, direct, never preachy. Relatable to nurses and anyone who has been a patient. Confident, not arrogant."],
    ["content_pillar_1", "Healthcare myths debunked — what the data actually says"],
    ["content_pillar_2", "Nurse life — behind the scenes in the ER, real stories"],
    ["content_pillar_3", "Mental health in healthcare — burnout, stress, ADHD"],
    ["content_pillar_4", "ADHD awareness — especially in underdiagnosed communities"],
    ["content_pillar_5", "Financial freedom for nurses — creating income outside the hospital"],
    ["tiktok_handle", "@nursecharles"],
    ["instagram_handle", "@nursecharles"],
    ["youtube_handle", ""],
    ["facebook_handle", ""],
    ["active_campaign", "Healthcare Creator Starter Kit"],
    ["active_product", "Healthcare Creator Starter Kit (FREE download)"],
    ["active_landing_page", ""],
    ["creator_1_name", ""],
    ["creator_1_platform", ""],
    ["creator_1_why", "Add during onboarding"],
    ["creator_2_name", ""],
    ["creator_2_platform", ""],
    ["creator_2_why", "Add during onboarding"],
    ["creator_3_name", ""],
    ["creator_3_platform", ""],
    ["creator_3_why", "Add during onboarding"],
    ["creator_4_name", ""],
    ["creator_4_platform", ""],
    ["creator_4_why", "Add during onboarding"],
    ["creator_5_name", ""],
    ["creator_5_platform", ""],
    ["creator_5_why", "Add during onboarding"],
]

# ── LL data ────────────────────────────────────────────────────────────────────
LL_SCRIPTS = [SCRIPTS_HEADER] + [
    ["Is Your Child Mouth Breathing?", "Video",
     "This one sign could change your child's entire development.",
     "[HOOK]\nThis one sign could change your child's entire development — and most parents miss it completely.\n\n[BODY]\nMouth breathing looks harmless. It is not. When children breathe through their mouth chronically, it changes the shape of their face, affects their sleep, and impacts cognitive development. I'm a myofunctional therapist and I see the effects every single day. Here are the 3 signs you need to look for tonight.\n\n[CTA]\nDownload my free parent's guide — link in bio.",
     "Free parent's guide — link in bio.", "posted", "ig,fb", "1", "Mon", "Parent's Guide to Myofunctional Therapy", "Child development", "April campaign #1", ""],
    ["5 Signs Your Child Needs a Consult", "Carousel",
     "If your child does any of these 5 things, it's time to act.",
     "SLIDE 1\nCover: 5 Signs Your Child May Need Myofunctional Therapy\n\nSLIDE 2\nSign 1: Open-mouth resting position\nIf their lips aren't touching when they're relaxed, that's a red flag.\n\nSLIDE 3\nSign 2: Snoring or restless sleep\nMouth breathing at night = poor sleep quality and less oxygen.\n\nSLIDE 4\nSign 3: Chewing with mouth open\nCould indicate a tongue thrust or oral motor weakness.\n\nSLIDE 5\nSign 4: Frequent ear infections or congestion\nThe nasal passage isn't filtering properly.\n\nSLIDE 6\nSign 5: Speech delays or lisping\nThe tongue position affects everything.\n\nSLIDE 7\nFinal: Schedule a consult. Early intervention changes outcomes.\n",
     "Schedule a free consult — link in bio.", "posted", "ig,fb", "1", "Tue", "Parent's Guide to Myofunctional Therapy", "Parenting tips", "April campaign #2", ""],
    ["What Is Myofunctional Therapy?", "Video",
     "Most dentists recommend it. Most parents have never heard of it.",
     "[HOOK]\nMost dentists recommend it. Most parents have never heard of it. What is myofunctional therapy?\n\n[BODY]\nMyofunctional therapy is exercise-based treatment for the muscles of the mouth, face, and throat. It addresses the root cause of mouth breathing, tongue thrust, sleep issues, and speech patterns — rather than just managing the symptoms. It's non-invasive, it works for children and adults, and it's one of the most underutilized tools in pediatric health. Here's exactly what happens in a session.\n\n[CTA]\nFree parent's guide in bio — everything you need to know before your first consult.",
     "Free parent's guide — link in bio.", "posted", "ig,fb", "1", "Wed", "Parent's Guide to Myofunctional Therapy", "Education", "April campaign #3", ""],
]

LL_SCHEDULE = [SCHEDULE_HEADER] + [
    ["Is Your Child Mouth Breathing?", "1", "Mon", "ig,fb"],
    ["5 Signs Your Child Needs a Consult", "1", "Tue", "ig"],
    ["What Is Myofunctional Therapy?", "1", "Wed", "ig,fb"],
]

LL_PROFILE = [PROFILE_HEADER] + [
    ["client_name", "Lasting Language"],
    ["full_name", "Amanda Smith"],
    ["niche", "Myofunctional Therapy & Children's Oral Health"],
    ["target_audience", "Parents of young children (ages 2-12), dentists and orthodontists who refer, families concerned about mouth breathing, speech delays, or sleep issues in children"],
    ["tone", "Warm, reassuring, and educational. Expert without being clinical. Speaks to anxious parents with compassion. Empowering — gives parents the language and confidence to advocate for their child. Never fear-mongering, always solution-focused."],
    ["content_pillar_1", "Mouth breathing awareness — signs, causes, and consequences"],
    ["content_pillar_2", "Myofunctional therapy explained — what it is, how it works, what to expect"],
    ["content_pillar_3", "Child development — sleep, speech, facial growth connections"],
    ["content_pillar_4", "Parent education — what to ask at the dentist, when to seek help"],
    ["content_pillar_5", "Before & after — real outcomes and client stories (HIPAA compliant)"],
    ["instagram_handle", "@lastinglanguage"],
    ["facebook_handle", ""],
    ["tiktok_handle", ""],
    ["youtube_handle", ""],
    ["active_campaign", "Parent's Guide to Myofunctional Therapy"],
    ["active_product", "Parent's Guide to Myofunctional Therapy (FREE download)"],
    ["active_landing_page", ""],
    ["creator_1_name", ""],
    ["creator_1_platform", ""],
    ["creator_1_why", "Add during onboarding"],
    ["creator_2_name", ""],
    ["creator_2_platform", ""],
    ["creator_2_why", "Add during onboarding"],
    ["creator_3_name", ""],
    ["creator_3_platform", ""],
    ["creator_3_why", "Add during onboarding"],
    ["creator_4_name", ""],
    ["creator_4_platform", ""],
    ["creator_4_why", "Add during onboarding"],
    ["creator_5_name", ""],
    ["creator_5_platform", ""],
    ["creator_5_why", "Add during onboarding"],
]

# ── Demo data ──────────────────────────────────────────────────────────────────
DEMO_SCRIPTS = [SCRIPTS_HEADER] + [
    ["The Content Strategy Nobody Talks About", "Video",
     "Most creators get this backwards — and it costs them everything.",
     "[HOOK]\nMost creators get this backwards — and it costs them everything.\n\n[BODY]\nEveryone focuses on going viral. But the creators who actually build businesses focus on something completely different. They build trust before they build reach. Here's the exact 3-step content strategy I use to turn viewers into clients — without chasing trends.\n\n[CTA]\nFree Content Starter Guide — link in bio.",
     "Free Content Starter Guide — link in bio.", "scheduled", "tiktok,ig,yt", "1", "Mon", "Content Starter Guide", "Creator strategy", "Week 1 flagship", ""],
    ["Why Your Hook Is Killing Your Retention", "Video",
     "Your hook got them to click. This is why they left in 3 seconds.",
     "[HOOK]\nYour hook got them to click. This is why they left in 3 seconds.\n\n[BODY]\nA good hook opens a loop. A great hook opens a loop AND makes leaving feel like a loss. Here's the difference between hooks that get clicks and hooks that get watch time — and the 5 hook formulas that consistently perform in every niche.\n\n[CTA]\nSave this and try one this week.",
     "Save this for your next script.", "scheduled", "tiktok,ig", "1", "Tue", "Content Starter Guide", "Hooks & retention", "Week 1", ""],
    ["5 Things Every Creator Needs Before They Monetize", "Carousel",
     "Monetizing too early is the #1 mistake new creators make.",
     "SLIDE 1\nCover: Don't monetize until you have these 5 things\n\nSLIDE 2\n#1: A clear niche and point of view\nYou need to be known for something specific.\n\nSLIDE 3\n#2: A conversion asset (lead magnet, freebie, or email list)\nSocial followers are rented. Email is owned.\n\nSLIDE 4\n#3: At least 30 pieces of published content\nConsistency builds trust before revenue.\n\nSLIDE 5\n#4: A defined audience avatar\nKnow exactly who you're talking to and what keeps them up at night.\n\nSLIDE 6\n#5: One clear offer\nNot five. Not two. One.\n\nSLIDE 7\nSave this checklist and revisit it monthly.\n",
     "Get the full monetization checklist — free in bio.", "scheduled", "ig", "1", "Wed", "Content Starter Guide", "Monetization", "Week 1 carousel", ""],
    ["Your First 1000 Followers", "Video",
     "Getting to 1K followers is 100% a psychology game.",
     "[HOOK]\nGetting to 1K followers is 100% a psychology game — and here's how to win it.\n\n[BODY]\nYour first 1000 followers aren't found. They're earned through specificity. The creators who blow past 1K fast all do one thing: they make the person watching feel like the video was made just for them. Here's how to create that feeling consistently.\n\n[CTA]\nFollow for the full audience growth series.",
     "Follow for the full growth series.", "draft", "tiktok,ig", "1", "Thu", "Content Starter Guide", "Growth tactics", "Week 1", ""],
    ["How I Plan 30 Days of Content in 2 Hours", "Video",
     "30 days of content. 2 hours. No burnout. Here's the system.",
     "[HOOK]\n30 days of content. 2 hours. No burnout. Here's the system.\n\n[BODY]\nContent burnout is real and it kills more creator businesses than bad content ever does. The solution isn't posting less. It's batching smarter. I'll show you the exact planning system I use every month — including the template I use to go from blank page to full calendar in under 2 hours.\n\n[CTA]\nContent planning template inside the free guide — link in bio.",
     "Free content planning template — link in bio.", "draft", "tiktok,ig,yt", "1", "Fri", "Content Starter Guide", "Productivity", "Week 1", ""],
]

DEMO_SCHEDULE = [SCHEDULE_HEADER] + [
    ["The Content Strategy Nobody Talks About", "1", "Mon", "tiktok,ig,yt"],
    ["Why Your Hook Is Killing Your Retention", "1", "Tue", "tiktok,ig"],
    ["5 Things Every Creator Needs Before They Monetize", "1", "Wed", "ig"],
    ["Your First 1000 Followers", "1", "Thu", "tiktok,ig"],
    ["How I Plan 30 Days of Content in 2 Hours", "1", "Fri", "tiktok,ig,yt"],
]

DEMO_PROFILE = [PROFILE_HEADER] + [
    ["client_name", "Demo Client"],
    ["full_name", "Your Name"],
    ["niche", "Content Creation & Personal Brand Building"],
    ["target_audience", "Aspiring creators, entrepreneurs, and personal brand builders who want to grow an audience and monetize their expertise"],
    ["tone", "Strategic, inspiring, and practical. Speaks as a peer who has figured it out. Direct, no fluff. Encouraging without being motivational-poster generic."],
    ["content_pillar_1", "Content strategy — how to plan, create, and distribute effectively"],
    ["content_pillar_2", "Audience growth — hooks, algorithms, consistency"],
    ["content_pillar_3", "Monetization — when and how to turn audience into income"],
    ["content_pillar_4", "Brand building — positioning, niche, point of view"],
    ["content_pillar_5", "Systems & tools — how to work smarter, batch content, avoid burnout"],
    ["tiktok_handle", "@yourcreatorhandle"],
    ["instagram_handle", "@yourcreatorhandle"],
    ["youtube_handle", "@yourcreatorhandle"],
    ["facebook_handle", ""],
    ["active_campaign", "Content Starter Guide"],
    ["active_product", "Content Starter Guide (FREE download)"],
    ["active_landing_page", ""],
    ["creator_1_name", ""],
    ["creator_1_platform", ""],
    ["creator_1_why", "Add during onboarding"],
    ["creator_2_name", ""],
    ["creator_2_platform", ""],
    ["creator_2_why", "Add during onboarding"],
    ["creator_3_name", ""],
    ["creator_3_platform", ""],
    ["creator_3_why", "Add during onboarding"],
    ["creator_4_name", ""],
    ["creator_4_platform", ""],
    ["creator_4_why", "Add during onboarding"],
    ["creator_5_name", ""],
    ["creator_5_platform", ""],
    ["creator_5_why", "Add during onboarding"],
]

# ── Sheet configs ──────────────────────────────────────────────────────────────
SHEETS = [
    {
        "id":      "1S7i7ao2c76YD-FGcKEsjRlggONsZgdrtfwm6MaLEDrc",
        "name":    "Demo",
        "scripts": DEMO_SCRIPTS,
        "schedule":DEMO_SCHEDULE,
        "profile": DEMO_PROFILE,
    },
    {
        "id":      "13CljMtzYauS9p5A4cK2YW30098ISFcxPDdCWsWK6etM",
        "name":    "Nurse Charles",
        "scripts": NC_SCRIPTS,
        "schedule":NC_SCHEDULE,
        "profile": NC_PROFILE,
    },
    {
        "id":      "1Oh2oA4yuRs1YDIs3sIW_zjd9ls-N3LPpGkU8hdVqDoM",
        "name":    "Lasting Language",
        "scripts": LL_SCRIPTS,
        "schedule":LL_SCHEDULE,
        "profile": LL_PROFILE,
    },
]

if __name__ == "__main__":
    token = get_token()
    for sheet in SHEETS:
        print(f"\n▶ {sheet['name']}")
        existing = get_tabs(token, sheet["id"])
        if "Client Profile" not in existing:
            add_tab(token, sheet["id"], "Client Profile")
        write_tab(token, sheet["id"], "Scripts",       sheet["scripts"])
        write_tab(token, sheet["id"], "Schedule",      sheet["schedule"])
        write_tab(token, sheet["id"], "Client Profile",sheet["profile"])
    print("\n✓ Done.")
