#!/usr/bin/env python3
"""Rebuild Content tab: split each short bundle into per-platform rows."""

import json, re, time, urllib.request, urllib.parse
from pathlib import Path

SHEET_ID = "1aCLZMcvLbacFHrZwuTBlgwezVHoAxFNYpmapqN9AVXY"
SHEETS_BASE = "https://sheets.googleapis.com/v4/spreadsheets"
GOOGLE_TOKEN_PATH = Path.home() / ".config/google-workspace-mcp/profiles/emerson-north/tokens.json"
GOOGLE_CREDS_PATH = Path.home() / ".config/google-workspace-mcp/profiles/emerson-north/credentials.json"

def get_access_token():
    tokens = json.loads(GOOGLE_TOKEN_PATH.read_text())
    if tokens.get("expiry"):
        expiry = tokens["expiry"]
        if isinstance(expiry, str):
            from datetime import datetime
            try:
                exp_time = datetime.fromisoformat(expiry.replace("Z", "+00:00")).timestamp()
            except:
                exp_time = 0
        else:
            exp_time = float(expiry)
        if time.time() < exp_time - 60:
            return tokens["token"]
    creds = json.loads(GOOGLE_CREDS_PATH.read_text())
    client_id = creds["installed"]["client_id"]
    client_secret = creds["installed"]["client_secret"]
    refresh_token = tokens["refresh_token"]
    data = urllib.parse.urlencode({
        "client_id": client_id, "client_secret": client_secret,
        "refresh_token": refresh_token, "grant_type": "refresh_token"
    }).encode()
    req = urllib.request.Request("https://oauth2.googleapis.com/token", data=data, method="POST")
    with urllib.request.urlopen(req) as r:
        result = json.loads(r.read())
    return result["access_token"]

def sheets_request(method, path, body=None):
    token = get_access_token()
    url = f"{SHEETS_BASE}/{path}"
    data = json.dumps(body).encode() if body else None
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("Authorization", f"Bearer {token}")
    req.add_header("Content-Type", "application/json")
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read())

def strip_source(text):
    return re.sub(r'\[SOURCE:[^\]]*\]', '', text or '').strip()

def parse_short_bundle(script_text):
    """Split bundled multi-platform short script into {platform: script_content}."""
    result = {}
    sections = re.split(r'\n\s*---\s*\n', script_text.strip())
    for section in sections:
        section = section.strip()
        if not section:
            continue
        lines = section.split('\n')
        header = lines[0].strip()
        if header.startswith('[') and header.endswith(']'):
            platform = header[1:-1]
            content = '\n'.join(lines[1:]).strip()
            result[platform] = content
    return result

# Platform name → normalized sheet value
PLATFORM_MAP = {
    'LinkedIn':        'LinkedIn',
    'LinkedIn B':      'LinkedIn',
    'Instagram Reels': 'Instagram Reels',
    'TikTok':          'TikTok',
    'YouTube Shorts':  'YouTube Shorts',
}

# Descriptive titles for each individual short
SHORT_TITLES = {
    'short1': {
        'LinkedIn':        'Braces Move Teeth — Swallowing Patterns Are What Makes Them Stay',
        'LinkedIn B':      'The Myo Referral Is Not a Red Flag',
        'Instagram Reels': '3 Reasons Parents Don\'t Act on the Myo Referral',
        'TikTok':          'What the Free Intake Consult Actually Looks Like',
        'YouTube Shorts':  '3 Reasons Orthodontic Patients Relapse Without Myo',
    },
    'short2': {
        'LinkedIn':        'Myo Therapy Is Not Speech Therapy for Pronunciation',
        'LinkedIn B':      'What the Myo Evaluation Covers — 5 Parts',
        'Instagram Reels': 'The Orthodontist Referral Matters More Than Most Parents Realize',
        'TikTok':          'What Actually Happens in a Myo Intake — 30 Seconds',
        'YouTube Shorts':  'The Most Common Misconception About Myo Therapy',
    },
    'short3': {
        'LinkedIn':        'The Credential and the System Are Two Different Things',
        'LinkedIn B':      'LSVT LOUD Is 16 Sessions Over 4 Weeks — Not One Session Per Week',
        'Instagram Reels': '3 Questions to Ask Before Booking a Parkinson\'s SLP',
        'TikTok':          'LSVT LOUD — What It Is and Why Most SLPs Aren\'t Certified',
        'YouTube Shorts':  'Same SLP Training, Different System, Different Outcomes',
    },
    'short4': {
        'LinkedIn':        'Ages 6–12 Is the Window When Myo Therapy Changes the Structure',
        'LinkedIn B':      'How We Divide Myo Treatment Into Phases After the Intake',
        'Instagram Reels': 'What the Myo Evaluation Measures — 5 Things in 30 Seconds',
        'TikTok':          'Why Your Orthodontist Referred for Myo — The Mechanism',
        'YouTube Shorts':  'Why Early Myo Therapy Has a Different Outcome',
    },
}

# Suffix letters for piece_id
SUFFIX_ORDER = ['LinkedIn', 'LinkedIn B', 'Instagram Reels', 'TikTok', 'YouTube Shorts']
SUFFIX_LETTER = {p: chr(ord('a') + i) for i, p in enumerate(SUFFIX_ORDER)}

# Bundle captions
BUNDLE_CAPTIONS = {
    'short1': 'The referral slip sitting on your counter? Here\'s what that actually means.\n\n#myotherapy #kidshealth',
    'short2': 'The window is smaller than most parents realize.\n\n#myotherapy #parenting #kidshealth',
    'short3': 'Hospital neuro rehab taught me things private practice never would have.\n\n#myotherapy #clinicianlife',
    'short4': 'One step at a time. No reason to wait.\n\n#myotherapy #parenting',
}

# Raw bundled scripts (keyed by piece_id)
BUNDLE_SCRIPTS = {
    'short1': """[LinkedIn]
[0:00] Amanda at desk, facing camera directly. Clinical but warm setting. No intro, no greeting.
[0:03] 'Braces move teeth. They do not change the swallowing pattern that caused the misalignment in the first place. And that distinction is exactly why your orthodontist gave you the myo referral.'
[0:14] Cut to Amanda gesturing, explaining mechanism.
[0:16] 'At rest, the tongue should sit gently against the roof of the mouth. Lips are closed. Breathing happens through the nose. When a child has a tongue thrust, the tongue pushes forward against the teeth instead. Every swallow. Five hundred to a thousand times per day. [SOURCE: proof_tongue_thrust_mechanism , "braces move teeth. But swallowing patterns will continue applying pressure afterward"]'
[0:34] Amanda holds up one finger.
[0:35] 'Braces apply a corrective force for 12, 18, 24 months. The tongue applies a counter-force for every waking hour after the braces come off. This is the primary driver of orthodontic relapse. Teeth shift. Gaps return. The orthodontist sees it.'
[0:52] Cut to graphic or text card: 'Tongue posture influences the muscles surrounding the teeth and jaw.'
[0:57] Amanda back on camera.
[0:58] 'Myofunctional therapy addresses the swallowing mechanics before or during orthodontic treatment, so that when the braces come off, the muscle environment supports the result. Not the referral working against it. The myo referral is not optional context. It is the piece that determines whether the orthodontic result holds. [SOURCE: proof_cmt_credential , "CMT credential, one of few in Atlanta metro"]'
[1:18] Slight pause, direct look at camera.
[1:19] 'If your child received an orthodontist referral for myo therapy, the link in the bio has more on what to do with it.'
[1:26] End card: Lasting Language Therapy logo + 'Free Intake Consult | lastinglanguagetherapy.com/myo-referral-welcome-kit'

---

[LinkedIn B]
[0:00] Amanda at desk. Direct to camera. No intro.
[0:02] 'If your orthodontist handed you a referral for myofunctional therapy, here is the one thing I want you to understand before you do anything else.'
[0:09] 'It is not a red flag. It is not saying something is wrong with your child. It is saying there is a specific muscle pattern, a tongue posture or a swallowing habit, that will work against what the braces are trying to accomplish.'
[0:22] 'Orthodontic treatment moves teeth into position. Myo therapy teaches the muscles to hold them there. One without the other is the reason so many families end up back in braces as adults.'
[0:38] 'That referral is the orthodontist catching this at the right time. The next step is booking a myo intake so we can evaluate exactly what the pattern looks like and build a plan.'
[0:52] 'The link to book is in my bio.'

---

[Instagram Reels]
[0:00] Amanda on camera, slightly casual framing, good light.
[0:02] 'A 123-comment thread on r/braces documented the same pattern: parents getting the orthodontist referral for myo therapy and not acting on it for weeks or months. Not because they did not care. [SOURCE: proof_rbraces_thread , "r/braces community thread, 123 comments"]'
[0:16] Cut rhythm, more direct.
[0:17] 'Three reasons this happens. One: the category is unfamiliar. Most parents have heard of speech therapy. Most have never heard of myofunctional therapy. So the first step is research, not booking, and research gets deferred.'
[0:28] Hold up second finger.
[0:29] 'Two: no one explained the mechanism. The ortho said get myo therapy but did not say: tongue posture determines whether your child\'s braces hold long-term. Without that context, the referral reads as optional.'
[0:38] Hold up third finger.
[0:39] 'Three: the specialist is genuinely hard to find. A Certified Myofunctional Therapist is not the same as a general SLP who covers myo on the side. The CMT credential is specific. [SOURCE: proof_cmt_credential , "CMT credential, one of few in Atlanta metro"] And in Atlanta, finding one positioned for exactly the post-referral moment is a real search gap.'
[0:55] Close.
[0:56] 'Link in bio. Free intake consult. One appointment.'

---

[TikTok]
[0:00] Amanda, direct to camera, relaxed energy.
[0:02] 'If you have been sitting on a myo referral from your orthodontist and the main reason you have not booked is that you do not know what you are walking into, this is for you.'
[0:10] Shift posture slightly, more conversational.
[0:11] 'The free intake consult at Lasting Language Therapy looks like this. You come in. We talk through what the orthodontist observed and what the referral actually means for your child\'s orthodontic outcome. [SOURCE: proof_ortho_implied_endorsement , "the referring professional already established the category"]'
[0:22] 'Then I do a brief functional assessment. I look at tongue posture, lip closure, swallowing mechanics, and mouth breathing patterns. At rest, the tongue should sit gently against the roof of the mouth. Lips closed. Nose breathing. I check what the actual pattern is.'
[0:35] 'And at the end, you get a plain-language answer. Does your child need myofunctional therapy? If yes, what does it look like? How long? How often?'
[0:42] 'No charge for the first visit. No obligation to continue. Link in bio.'
[0:46] End frame: 'Free Intake Consult | lastinglanguagetherapy.com/myo-referral-welcome-kit'

---

[YouTube Shorts]
[0:00] Amanda facing camera, casual setting. Direct, warm delivery.
[0:02] 'Three reasons orthodontic patients relapse without myo therapy.'
[0:06] 'Number one: tongue thrust. That is 500 to 1,000 repetitions of forward tongue pressure against the teeth every single day. Braces cannot compete with that.'
[0:18] 'Number two: mouth breathing. When a child breathes through the mouth at rest, the tongue drops from the palate. That changes how the jaw develops.'
[0:28] 'Number three: low tongue posture. The tongue acts as a natural retainer when it rests correctly. Without that, teeth drift.'
[0:40] 'Myo therapy addresses all three. If your orthodontist referred your child, this is exactly why. Book a myo intake, link in bio.'
[0:54] End card.""",

    'short2': """[LinkedIn]
[0:00] Camera straight on, clinical setting, Amanda seated at desk. No intro music. Cut straight to face.
[0:03] 'The most common thing I see when a parent walks into a myo intake appointment is this: they think we\'re going to work on their child\'s speech sounds.'
[0:10] 'They come in expecting articulation drills. They think myo therapy is speech therapy for pronunciation.'
[0:16] 'It\'s not.'
[0:18] 'Myo therapy addresses the muscle function patterns that affect dental alignment, airway health, and sleep quality. We are working on tongue posture. Oral rest posture. Swallowing mechanics. Nasal breathing habits.'
[0:30] B-roll or camera hold: Amanda at desk, writing or reviewing notes.
[0:33] 'At rest, the tongue should sit gently against the roof of the mouth. Lips are closed. Breathing happens through the nose. When those patterns are off, the pressure from every swallow, and a child swallows between 500 and 1,000 times a day, that pressure keeps working against the teeth.'
[0:50] 'I came from hospital acute care. Stroke, TBI, Parkinson\'s. When I moved into private practice, I carried my old clinical lens with me longer than I should have. That changed when an orthodontist referral showed me what two prior SLPs had missed.'
[1:10] 'The ortho referral is not a suggestion. It\'s a clinical observation from someone who has examined your child\'s oral structures closely.'
[1:18] 'If you have that referral and you\'re not sure what to do next, follow @lastinglanguage. The link in my bio takes you to our free resource library.'

---

[LinkedIn B]
[0:00] Amanda at desk, composed. Clinical setting.
[0:02] 'When a family comes in for a myo intake after an orthodontic referral, parents usually expect something resembling speech therapy. What they get is different.'
[0:12] 'The evaluation has five parts. First: tongue posture at rest. Is the tongue on the palate or on the floor of the mouth? Second: lip seal. Third: jaw symmetry and development. Fourth: nasal versus oral breathing pattern. Fifth: the swallow.'
[0:32] 'We film the swallow. We photograph the rest posture. We chart what we find and map it to the orthodontic concern the referral describes.'
[0:42] 'Parents leave the intake knowing exactly what we found, what it connects to in terms of the orthodontic timeline, and what the first phase of therapy addresses.'
[0:55] 'Intake booking link is in my bio.'

---

[Instagram Reels]
[0:00] Straight to face, no preamble. Casual setting or simple background.
[0:02] 'Five years ago I would not have told you that an orthodontist referral is sometimes the most important piece of clinical information a child gets.'
[0:10] 'Now I would.'
[0:12] 'The ortho sees tongue thrust. They see low oral rest posture. They see the way swallowing patterns are applying pressure to teeth that are being moved by braces. That\'s the connection that often gets missed in standard outpatient speech evaluations.'
[0:26] 'Tongue posture influences the muscles surrounding the teeth and jaw. Braces move the teeth. Swallowing patterns keep applying pressure afterward.'
[0:36] 'If your ortho referred your child for myofunctional therapy, that referral matters. Don\'t let it sit on the counter.'
[0:42] 'Link in bio. Free intake consult for Atlanta families.'

---

[TikTok]
[0:00] Cut straight in. Close frame on Amanda.
[0:01] 'What actually happens in a myo intake appointment. Thirty seconds, no fluff.'
[0:05] 'First I ask the parent what the ortho said. Word for word. Because what the ortho said and what the parent heard are usually two different things.'
[0:12] 'Then I observe the child before I ask them anything. Where does the tongue sit at rest? Are the lips closed? Are they breathing through the nose or the mouth?'
[0:20] 'Then the clinical piece. Tongue posture. Oral rest posture. Lip seal. Swallowing mechanics. I have the child swallow and I watch for a tongue thrust pattern, meaning the tongue pushes forward instead of pressing up against the roof of the mouth.'
[0:32] 'That forward pressure doesn\'t stop because you put braces on. That\'s the whole reason the ortho referred.'
[0:38] 'The intake takes about an hour. You leave knowing exactly what your child needs. Follow for more.'

---

[YouTube Shorts]
[0:00] Amanda, casual and direct. No intro.
[0:02] 'Most common misconception parents have about myo therapy: they think it is for speech sounds. It is not.'
[0:10] 'Myofunctional therapy addresses tongue posture, lip seal, jaw development, breathing patterns, and the swallow. Those are the muscle functions that influence how teeth move and how the airway develops.'
[0:25] 'When your orthodontist refers your child for myo, they are not saying your child has a speech delay. They are saying there is a muscle pattern that will work against the orthodontic treatment.'
[0:38] 'The intake takes about an hour. We look at rest posture, we film the swallow, we map what we find to your child\'s orthodontic plan.'
[0:50] 'You leave knowing exactly what is happening and what comes next. Booking link in bio.'
[1:00] End.""",

    'short3': """[LinkedIn]
[0:00] Amanda at desk, facing camera directly. No greeting. Immediate.
[0:02] 'I want to say something that took me years in hospital SLP to be able to articulate clearly. The credential and the system are two different things. The hospital gave me the best clinical training available. The system structurally could not give patients what they needed. Both of those are true at the same time.'
[0:18] Pause. Slightly more direct.
[0:19] 'The case that clarified it for me was Parkinson\'s voice therapy. LSVT LOUD is a 16-session, four-week protocol at four sessions per week. That structure is not administrative convenience. The intensity is the intervention.'
[0:40] Cut. More forward energy.
[0:41] 'What does an outpatient insurance-based setting actually schedule for a Parkinson\'s patient? One session per week. Sometimes two. At 30 to 45 minutes. That is not LSVT LOUD. That is a different thing with the same name applied loosely. And families often have no way to know the difference.'
[0:58] Brief pause.
[0:59] 'I left because I wanted to actually run the protocol. That means a private practice model where session frequency is determined by what the evidence says patients need, not what the schedule can accommodate. That is the practice I built.'
[1:16] Close.
[1:17] 'If you are a caregiver for a Parkinson\'s patient and you want to understand what the right speech intervention actually looks like, the link in the bio has more. Or reach out directly.'

---

[LinkedIn B]
[0:00] Amanda at desk. Composed, clear, direct.
[0:02] 'LSVT LOUD is a 16-session protocol delivered four times per week over four weeks. That is the clinical standard. That is what the research shows works for Parkinson\'s patients.'
[0:14] 'Most outpatient settings schedule those same patients once per week. Which means a four-week evidence-based protocol gets stretched over four months.'
[0:24] 'I am not saying those clinicians do not care. I am saying the system does not have room for the protocol. And that is a real problem for patients who need it to work.'
[0:35] 'When I opened my private practice, the ability to actually deliver LSVT the way it was designed to be delivered was one of the first things I built around. Patients notice. The outcomes show it.'
[0:50] 'If you are a Parkinson\'s patient or family member in the Atlanta area, the intake link is in my bio.'

---

[Instagram Reels]
[0:00] Amanda, warm but direct. Reels framing.
[0:02] 'If your family member has Parkinson\'s disease and a neurologist told you to see a speech-language pathologist for the voice changes, here are three specific questions to ask before you book.'
[0:12] Hold up one finger.
[0:13] 'First: Are you LSVT LOUD certified? This is a yes or no question. The certification requires specific formal training. It is not a continuing education credit. A certified provider has been trained in the actual protocol.'
[0:26] Second finger.
[0:27] 'Second: What does your session schedule look like for Parkinson\'s patients? If the answer is one session per week at 45 minutes, that is not the LSVT LOUD protocol. The protocol is four sessions per week. The intensity is the intervention.'
[0:38] Third finger.
[0:39] 'Third: Do you also monitor swallowing mechanics? Parkinson\'s affects swallowing in addition to voice. A Parkinson\'s SLP who only treats the voice is working with incomplete context. Ask about both.'
[0:52] Close.
[0:53] 'Three questions. Ask them before the first session. Link in bio for more on what Parkinson\'s speech therapy should look like.'

---

[TikTok]
[0:00] Amanda, direct. No lead-in.
[0:02] 'LSVT LOUD is the gold-standard voice therapy for Parkinson\'s disease. Here is what it actually is and why most SLPs are not certified to run it.'
[0:10] Explaining mode, but quick.
[0:11] 'Parkinson\'s creates a calibration error. The brain stops accurately perceiving how loud the patient is actually speaking. The patient thinks their voice is normal volume. Everyone around them can barely hear them. Generic voice therapy that tells the patient to speak louder does not recalibrate the system. LSVT LOUD does.'
[0:26] Cut, slightly more energized.
[0:27] 'The protocol is 16 sessions over 4 weeks at four sessions per week. Each session is one hour. That frequency is not arbitrary. It is what the research showed is required to produce the neurological reorganization. You cannot run it correctly at one session per week.'
[0:40] Direct close.
[0:41] 'Most SLPs are not LSVT LOUD certified because the training requires completing a specific formal program. General voice therapy knowledge is not the same thing. When you are choosing an SLP for Parkinson\'s, ask if they are certified. That one question changes the conversation. Link in bio.'

---

[YouTube Shorts]
[0:00] Amanda, direct to camera, relaxed but clear.
[0:02] 'I spent years in hospital acute care doing SLP work with stroke survivors, Parkinson\'s patients, TBI cases.'
[0:10] 'When I went into private practice, the clinical training was the same. What changed was how much time I had per patient, how often I could see them, and how closely I could follow the protocols that actually work.'
[0:26] 'In hospital, you get 30 to 45 minutes, once or twice a week, in a shared space. In private practice, sessions are longer. Scheduling is built around the protocol, not the other way around.'
[0:40] 'Same SLP training. Different system. Different outcomes.'
[0:48] 'If you are a Parkinson\'s patient looking for LSVT LOUD in the Atlanta area, the booking link is in my bio.'
[0:58] End.""",

    'short4': """[LinkedIn]
[0:00] Amanda at desk or standing beside a printed anatomy diagram. Direct to camera.
[0:02] 'Between ages 6 and 12, the jaw and palate are still actively developing. That is not a generalization. That is a clinical fact with direct implications for myofunctional therapy outcomes.'
[0:15] 'During this window, the palate is still malleable. Muscle function patterns, including tongue posture, swallowing mechanics, and oral rest posture, directly influence the shape of the dental arch and the development of the airway.'
[0:27] 'When we address a tongue thrust or low tongue posture during this window, we\'re not just correcting a habit. We\'re supporting structural development that\'s happening in real time.'
[0:38] 'For children outside this window, myo therapy is still effective. I want to be clear about that. Adults complete myo therapy successfully. But the structural malleability that makes ages 6 to 12 significant is no longer a factor.'
[0:52] 'So if your child\'s orthodontist referred for myo therapy and your child is in that 6 to 12 range, that is the most relevant clinical reason to act now.'
[1:02] 'The intake consult is free. No charge. No obligation. You come in, we evaluate tongue posture, swallowing mechanics, lip seal, and nasal breathing patterns. You leave knowing exactly where your child stands.'
[1:15] 'Link in my bio. Lasting Language Therapy, Sandy Springs, Georgia. Follow for more on myofunctional therapy and pediatric oral health.'

---

[LinkedIn B]
[0:00] Amanda at desk. Professional framing. No intro.
[0:02] 'After the myo intake, we divide treatment into phases. Phase one addresses the pattern that has the most direct impact on the orthodontic concern the referral describes.'
[0:13] 'Usually that is tongue posture at rest and the swallow. Those are the two patterns creating the most active pressure against the teeth.'
[0:22] 'Each phase runs six to eight weeks. Progress is measured against the baseline we documented at intake, not against a general checklist. The orthodontist receives a progress note after phase one so they can coordinate timing with the next stage of treatment.'
[0:40] 'Why phases? Because the goal is a sustained habit change, not a temporary correction. The muscle has to learn the new pattern under load, across activities, over time.'
[0:55] 'Intake link is in bio if your child has been referred.'

---

[Instagram Reels]
[0:00] Fast cut, direct to camera, clinical or neutral background.
[0:01] 'What the myo evaluation actually measures. Five things in thirty seconds.'
[0:05] 'One: tongue posture at rest. Where does the tongue sit when your child is not talking or eating? It should be gently against the roof of the mouth, not low or forward.'
[0:13] 'Two: oral rest posture. Are the lips closed at rest? Is the jaw relaxed? Lip closure matters because it tells us about mouth breathing habits.'
[0:21] 'Three: nasal versus mouth breathing patterns. Does your child sleep with their mouth open? Breathe audibly at rest?'
[0:27] 'Four: lip seal and lip strength.'
[0:30] 'Five: swallowing mechanics. This is the big one. A tongue thrust, meaning the tongue pushes forward during every swallow, keeps applying pressure to teeth that braces are trying to move into alignment.'
[0:42] 'That\'s what the evaluation covers. Link in bio if you have an ortho referral and want to book the free intake.'

---

[TikTok]
[0:00] Straight cut, close frame, Amanda speaking directly.
[0:01] 'Why did your orthodontist refer your child for myo therapy? Here\'s the mechanism in thirty seconds.'
[0:06] 'Braces move teeth into alignment. But swallowing patterns keep applying pressure afterward.'
[0:12] 'A tongue thrust swallowing pattern means the tongue pushes forward against the front teeth with every swallow. A child swallows somewhere between 500 and 1,000 times per day.'
[0:22] 'That forward pressure works against orthodontic treatment. It can push teeth back out of alignment after braces come off.'
[0:28] 'Myo therapy addresses the swallowing mechanics, tongue posture, and oral rest posture that make orthodontic results last.'
[0:35] 'Free intake consult if you have an ortho referral. Link in bio.'

---

[YouTube Shorts]
[0:00] Amanda, direct to camera. Informational but accessible.
[0:02] 'Between ages 6 and 12, the jaw and palate are still actively developing. That developmental window is why early myo therapy has a different outcome than the same therapy in a teenager or adult.'
[0:16] 'At this age, we are not just correcting a habit. We are working with tissue that is still plastic. The palate can widen. The jaw can be shaped by the forces acting on it. The airway responds.'
[0:30] 'When your orthodontist refers a child in this age range for myo therapy, the timing is intentional. They are trying to use that developmental window before it closes.'
[0:43] 'A myo intake at age seven or eight can change the trajectory of orthodontic treatment entirely. Sometimes significantly.'
[0:55] 'Intake booking link is in my bio. If your child is in this age range and has been referred, do not wait.'
[1:03] End.""",
}

# Schedule info for each bundle (week, day, date)
BUNDLE_SCHEDULE = {
    'short1': ('1', 'Tue', '2026-04-15'),
    'short2': ('1', 'Thu', '2026-04-17'),
    'short3': ('2', 'Tue', '2026-04-22'),
    'short4': ('2', 'Thu', '2026-04-24'),
}

def build_short_rows():
    rows = []
    for bundle_id in ['short1', 'short2', 'short3', 'short4']:
        week, day, date = BUNDLE_SCHEDULE[bundle_id]
        caption = BUNDLE_CAPTIONS[bundle_id]
        parsed = parse_short_bundle(BUNDLE_SCRIPTS[bundle_id])
        for platform in SUFFIX_ORDER:
            if platform not in parsed:
                continue
            suffix = SUFFIX_LETTER[platform]
            piece_id = f"{bundle_id}{suffix}"
            title = SHORT_TITLES[bundle_id][platform]
            script = strip_source(parsed[platform])
            sheet_platform = PLATFORM_MAP[platform]
            rows.append([piece_id, title, 'Short-Form Video', sheet_platform, week, day, date, script, caption, 'Draft', '', ''])
    return rows

def main():
    # Read existing content_rows.json to get the non-short rows
    existing = json.loads(Path("/Users/bryce/FLSM/.tmp/content_rows.json").read_text())
    all_rows = existing["values"]  # includes header

    header = all_rows[0]
    data_rows = all_rows[1:]

    # Keep non-short rows
    non_short = [r for r in data_rows if not r[0].startswith('short')]
    # Build individual short rows
    short_rows = build_short_rows()

    print(f"Non-short rows: {len(non_short)}")
    print(f"Individual short rows: {len(short_rows)}")

    # Rebuild full dataset: header + non-short rows (with shorts inserted at right positions)
    # Order: build sorted list based on date, day sort
    DAYS_ORDER = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    TYPE_ORDER = {'YouTube Long-Form': 0, 'Short-Form Video': 1, 'LinkedIn Carousel': 2, 'IG/TT Carousel': 3, 'Blog Post': 4, 'Email': 5}

    all_data = non_short + short_rows
    def sort_key(r):
        week = int(r[4]) if r[4].isdigit() else 99
        day_idx = DAYS_ORDER.index(r[5]) if r[5] in DAYS_ORDER else 99
        type_idx = TYPE_ORDER.get(r[2], 10)
        piece_id = r[0]
        return (week, day_idx, type_idx, piece_id)

    all_data.sort(key=sort_key)

    final_values = [header] + all_data
    print(f"Total rows (with header): {len(final_values)}")
    for r in all_data:
        print(f"  {r[0]:12s} | {r[1][:50]:50s} | {r[3]:20s} | {r[6]}")

    # Write to sheet
    encoded_range = urllib.parse.quote("Content!A1")

    # First clear the sheet beyond the new data range
    clear_result = sheets_request("POST", f"{SHEET_ID}/values/Content!A1:L100:clear")

    # Write new data
    body = {
        "range": "Content!A1",
        "majorDimension": "ROWS",
        "values": final_values
    }
    result = sheets_request("PUT", f"{SHEET_ID}/values/{encoded_range}?valueInputOption=RAW", body)
    print(f"\nSuccess: {result.get('updatedRows', 0)} rows, {result.get('updatedCells', 0)} cells written")
    print(f"Range: {result.get('updatedRange', '')}")

if __name__ == "__main__":
    main()
