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

if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
        sys.stderr.reconfigure(encoding='utf-8')
    except Exception:
        pass

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

with sync_playwright() as p:
    print("[1/3] Khởi chạy Chrome Stealth Headless...")
    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=1600,1000"
        ]
    )
    page = context.pages[0] if context.pages else context.new_page()

    # 1. Analytics Overview
    print("[2/3] Kiểm tra số liệu Analytics hôm nay...")
    page.goto("https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/analytics/tab-overview", wait_until="domcontentloaded")
    time.sleep(6)
    page.screenshot(path="downloads/today_analytics_11_10.png")
    print("✓ Đã lưu ảnh chụp Analytics: downloads/today_analytics_11_10.png")

    # Extract metrics text
    try:
        metric_cards = page.locator("layout-row#cards, ytcp-metric-card, ytcp-card").all_inner_texts()
        print("Metric Cards:\n" + "\n---\n".join([m.strip() for m in metric_cards if m.strip()]))
    except Exception as e:
        print(f"Lỗi đọc metric: {e}")

    # Extract Realtime box
    try:
        realtime = page.locator("#realtime-summary, ytcp-realtime-card").all_inner_texts()
        print("Realtime Box:\n" + "\n---\n".join([r.strip() for r in realtime if r.strip()]))
    except Exception as e:
        print(f"Lỗi đọc realtime: {e}")

    # 2. Videos list status
    print("[3/3] Kiểm tra danh sách video...")
    page.goto("https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/videos/upload", wait_until="domcontentloaded")
    time.sleep(5)
    page.screenshot(path="downloads/today_videos_11_10.png")
    print("✓ Đã lưu ảnh chụp Videos: downloads/today_videos_11_10.png")

    rows = page.locator("ytcp-video-row").all()
    print(f"\nDanh sách {len(rows)} video dài:")
    for r in rows:
        try:
            title = r.locator("#video-title").inner_text().strip() if r.locator("#video-title").is_visible() else ""
            vis = r.locator(".tablecell-visibility, #visibility-state").inner_text().strip() if r.locator(".tablecell-visibility, #visibility-state").is_visible() else ""
            date_col = r.locator(".tablecell-date").inner_text().strip() if r.locator(".tablecell-date").is_visible() else ""
            views = r.locator(".tablecell-views").inner_text().strip() if r.locator(".tablecell-views").is_visible() else "0"
            comments = r.locator(".tablecell-comments").inner_text().strip() if r.locator(".tablecell-comments").is_visible() else "0"
            likes = r.locator(".tablecell-likes").inner_text().strip() if r.locator(".tablecell-likes").is_visible() else "0"
            print(f"  • {title} | Trạng thái: {vis} | Ngày: {date_col} | Views: {views} | Likes: {likes} | Comments: {comments}")
        except Exception:
            pass

    context.close()
    print("✓ Hoàn tất kiểm tra Studio hôm nay!")
