import sys, time
from pathlib import Path
sys.path.append(str(Path("05_Production_Pipeline").resolve()))
from invisible_playwright import InvisiblePlaywright
from muse_invpw_driver import DEFAULT_PROFILE

def test_hatch_token():
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        page.goto("https://muse.ai/thread/new", wait_until="domcontentloaded", timeout=30000)
        time.sleep(3)
        
        # Test manual fetch
        res = page.evaluate("""async () => {
            try {
                const r = await fetch('/api/hatch/token', {
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json',
                    },
                    body: JSON.stringify({})
                });
                const status = r.status;
                const text = await r.text();
                return { status, text };
            } catch (err) {
                return { error: err.toString() };
            }
        }""")
        print("Manual fetch /api/hatch/token result:", res)
        
        # Also check /api/hatch/vm/wake
        res_wake = page.evaluate("""async () => {
            try {
                const r = await fetch('/api/hatch/vm/wake', {
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json',
                    },
                    body: JSON.stringify({})
                });
                const status = r.status;
                const text = await r.text();
                return { status, text };
            } catch (err) {
                return { error: err.toString() };
            }
        }""")
        print("Manual fetch /api/hatch/vm/wake result:", res_wake)

if __name__ == '__main__':
    test_hatch_token()
