import time
import json
from pathlib import Path
from playwright.sync_api import sync_playwright

profile_dir = Path("content/browser_profiles/chrome_mirsixabcf2").resolve()
extension_dir = Path("extension").resolve()

with sync_playwright() as p:
    context = p.chromium.launch_persistent_context(
        user_data_dir=str(profile_dir),
        channel="chrome",
        headless=True,
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        args=[
            f"--load-extension={extension_dir}",
            "--disable-blink-features=AutomationControlled",
            "--window-size=1440,900"
        ]
    )
    page = context.pages[0] if context.pages else context.new_page()
    page.goto("https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/videos/upload", wait_until="domcontentloaded")
    time.sleep(5)
    
    # Check claim text on Ep 3
    rows = page.locator("ytcp-video-row").all()
    for r in rows:
        title = r.locator("#video-title").inner_text() if r.locator("#video-title").is_visible() else ""
        if "Ep 3" in title or "Gia Dinh" in title:
            restr = r.locator(".tablecell-restrictions, #restrictions-text").inner_text() if r.locator(".tablecell-restrictions, #restrictions-text").is_visible() else "N/A"
            print(f"Target row: {title} | Restrictions: {restr}")
            # Hover over restriction
            badge = r.locator(".tablecell-restrictions").first
            if badge.is_visible():
                badge.hover()
                time.sleep(2)
                page.screenshot(path="downloads/ep3_hover_claim.png")
            break

    # Shorts tab
    print("\n--- SHORTS TAB ---")
    page.goto("https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/videos/short", wait_until="domcontentloaded")
    time.sleep(5)
    page.screenshot(path="downloads/studio_shorts.png")
    shorts_rows = page.locator("ytcp-video-row").all()
    print(f"Total shorts in studio: {len(shorts_rows)}")
    for sr in shorts_rows:
        try:
            stitle = sr.locator("#video-title").inner_text().strip()
            sviews = sr.locator(".tablecell-views").inner_text().strip()
            sdate = sr.locator(".tablecell-date").inner_text().strip()
            print(f"Short: {stitle} | Views: {sviews} | Date: {sdate}")
        except Exception:
            pass

    # Analytics tab
    print("\n--- ANALYTICS TAB ---")
    page.goto("https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/analytics/tab-overview", wait_until="domcontentloaded")
    time.sleep(6)
    page.screenshot(path="downloads/studio_analytics.png")
    
    context.close()
    print("Done inspecting.")
