#!/usr/bin/env python3
"""
Reschedule a Launch27 booking via Playwright.
Usage: python3 reschedule-booking.py <booking_id> <new_date_YYYY-MM-DD> [preferred_time]
preferred_time: exact start time, e.g. "10:00AM" matches "10:00AM - 12:00PM"
"""

import sys
import asyncio
from datetime import datetime
from playwright.async_api import async_playwright

BOOKING_ID = sys.argv[1] if len(sys.argv) > 1 else "77663"
NEW_DATE = sys.argv[2] if len(sys.argv) > 2 else "2026-04-11"
PREFERRED_TIME = sys.argv[3] if len(sys.argv) > 3 else "10:00AM"

dt = datetime.strptime(NEW_DATE, "%Y-%m-%d")
NEW_DATE_DISPLAY = dt.strftime("%m/%d/%Y")

EMAIL = "mike@nomorechores.com"
PASSWORD = "er!NCY73J"
BASE_URL = "https://nomorechores.launch27.com"

async def reschedule():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await browser.new_page()
        page.set_default_timeout(30000)

        print(f"Logging into Launch27...")
        await page.goto(f"{BASE_URL}/login", wait_until="networkidle")
        await page.wait_for_timeout(2000)

        await page.fill('input[ng-model="ctrl.user.email"]', EMAIL)
        await page.fill('input[ng-model="ctrl.user.password"]', PASSWORD)
        await page.click('button:has-text("Sign In")')
        await page.wait_for_load_state("networkidle")
        await page.wait_for_timeout(2000)

        if "login" in page.url:
            print("Login failed.")
            await browser.close()
            return False

        print("Logged in!")

        # Go to booking edit page
        await page.goto(f"{BASE_URL}/admin/bookings/{BOOKING_ID}/edit", wait_until="domcontentloaded")
        await page.wait_for_timeout(6000)
        print(f"On: {page.url}")

        # Set the date
        date_el = await page.query_selector('input[ng-model="ctrl.date"]')
        if not date_el:
            print("Date field not found!")
            await browser.close()
            return False

        old_date = await date_el.input_value()
        print(f"Current date: {old_date} → setting to: {NEW_DATE_DISPLAY}")

        await date_el.click(click_count=3)
        await date_el.type(NEW_DATE_DISPLAY)
        await date_el.press("Tab")
        await page.wait_for_timeout(3000)

        new_date_val = await date_el.input_value()
        print(f"Date field: {new_date_val}")

        # Find the time dropdown
        time_sel = await page.query_selector('select[ng-model*="spot"]')
        if not time_sel:
            print("Time dropdown not found!")
            await browser.close()
            return False

        # Get available options and find the RIGHT one
        # Match: option text must START with PREFERRED_TIME (e.g. "10:00AM")
        options = await time_sel.query_selector_all('option')
        print(f"Time slot options ({len(options)} total):")
        chosen = None
        for opt in options:
            txt = (await opt.inner_text()).strip()
            val = await opt.get_attribute('value') or ''
            if txt:
                print(f"  '{txt}' (value={val})")
            # Match: option must START with preferred time (not just contain it)
            if val and txt.upper().startswith(PREFERRED_TIME.upper()) and chosen is None:
                chosen = val
                print(f"  ^^^ SELECTED")

        if chosen is None:
            print(f"\nCould not find time slot starting with '{PREFERRED_TIME}'.")
            print("Available options above. Aborting.")
            await browser.close()
            return False

        # Select the time
        await time_sel.select_option(value=chosen)
        await page.wait_for_timeout(1500)
        print(f"Time slot selected.")
        await page.evaluate("(el) => el.dispatchEvent(new Event('change'))", time_sel)
        await page.wait_for_timeout(1000)

        await page.screenshot(path="/Users/harvey/.openclaw/workspace/l27-ready-to-save.png")

        # Click Save Changes
        save_link = await page.query_selector('a[ng-click="ctrl.saveBooking()"]')
        if not save_link:
            print("Save button not found!")
            await browser.close()
            return False

        print("Clicking 'Save Changes'...")
        await save_link.click()
        await page.wait_for_timeout(3000)

        # Check if a modal appeared (recurring booking dialog)
        modal = await page.query_selector('.modal, [role="dialog"], .modal-dialog')
        if modal:
            modal_text = await modal.inner_text()
            print(f"Modal appeared: {modal_text[:200]}")

            # We want "as Normal" — only change this one booking
            # Find the "as Normal" radio button
            as_normal = None
            radios = await modal.query_selector_all('input[type="radio"]')
            for radio in radios:
                ng = await radio.get_attribute('ng-model') or ''
                val = await radio.get_attribute('value') or ''
                # The "as Normal" option keeps future bookings as-is
                label = ''
                try:
                    parent = await radio.evaluate_handle('el => el.closest("label") || el.parentElement')
                    label = await parent.inner_text()
                except:
                    pass
                print(f"  Radio: ng-model={ng} value={val} label='{label[:60]}'")
                if 'normal' in label.lower() or 'normal' in val.lower():
                    as_normal = radio

            if as_normal:
                await as_normal.click()
                print("Selected 'as Normal' (keep future bookings unchanged)")
                await page.wait_for_timeout(500)
            else:
                print("Could not find 'as Normal' radio. Will use whatever is selected.")

            # Click the Save button in the modal
            modal_save = await modal.query_selector('button:has-text("Save"), a:has-text("Save"), input[value*="Save"]')
            if modal_save:
                print("Clicking modal Save button...")
                await modal_save.click()
            else:
                # Try page-level
                btns = await page.query_selector_all('button')
                for btn in btns:
                    txt = (await btn.inner_text()).strip()
                    if 'save' in txt.lower() and 'cancel' not in txt.lower():
                        print(f"Clicking button: '{txt}'")
                        await btn.click()
                        break

        await page.wait_for_timeout(5000)
        await page.screenshot(path="/Users/harvey/.openclaw/workspace/l27-after-save.png")
        print(f"After save URL: {page.url}")

        # Verify
        text = await page.evaluate("() => document.body.innerText")
        print(f"Page text (first 300): {text[:300]}")

        new_date_formatted = dt.strftime("%B %-d, %Y")
        if new_date_formatted in text:
            print(f"\n✅ SUCCESS: Booking rescheduled to {new_date_formatted}!")
        else:
            print(f"\n⚠️ Check l27-after-save.png to confirm.")

        await browser.close()
        return True

asyncio.run(reschedule())
