import json, sys, time
from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout

SITES = {
    "aman":      "https://www.aman.com/",
    "habitas":   "https://www.ourhabitas.com/",
    "sixsenses": "https://www.sixsenses.com/en/",
}

OUT_DIR = "/home/sirdrez/arisingmedia-websites/bigbreath.co/.planning/ref-styles"

COOKIE_SELECTORS = [
    "button[id*='accept']", "button[class*='accept']",
    "button[id*='cookie']", "button[class*='cookie']",
    "[aria-label*='Accept']", "[data-testid*='accept']",
    "button:has-text('Accept')", "button:has-text('Accept all')",
    "button:has-text('I agree')", "button:has-text('Got it')",
    "button:has-text('OK')", "button:has-text('Continue')",
]

EXTRACT_JS = """
() => {
    function cs(el) {
        if (!el) return null;
        const s = window.getComputedStyle(el);
        return {
            fontFamily: s.fontFamily,
            fontSize: s.fontSize,
            fontWeight: s.fontWeight,
            lineHeight: s.lineHeight,
            letterSpacing: s.letterSpacing,
            textTransform: s.textTransform,
            color: s.color,
            backgroundColor: s.backgroundColor,
            paddingTop: s.paddingTop,
            paddingBottom: s.paddingBottom,
            paddingLeft: s.paddingLeft,
            paddingRight: s.paddingRight,
            marginTop: s.marginTop,
            marginBottom: s.marginBottom,
            minHeight: s.minHeight,
            height: s.height,
            maxWidth: s.maxWidth,
            gap: s.gap,
            borderRadius: s.borderRadius,
        };
    }

    // Body
    const body = cs(document.body);

    // Hero: first large section or header or div with high z-index background
    const heroSelectors = [
        'section:first-of-type', 'header', '.hero', '#hero',
        '[class*="hero"]', '[class*="banner"]', '[class*="intro"]',
        'main > section:first-child', 'main > div:first-child',
    ];
    let heroEl = null;
    for (const sel of heroSelectors) {
        heroEl = document.querySelector(sel);
        if (heroEl && heroEl.getBoundingClientRect().height > 200) break;
    }
    const hero = cs(heroEl);

    // Hero H1
    const h1El = heroEl ? heroEl.querySelector('h1') || document.querySelector('h1') : document.querySelector('h1');
    const h1 = cs(h1El);

    // Eyebrow/sublabel in hero
    const eyebrowSelectors = [
        '[class*="eyebrow"]', '[class*="label"]', '[class*="sub"]',
        '[class*="overline"]', '[class*="caption"]', 'p:first-child',
    ];
    let eyebrowEl = null;
    if (heroEl) {
        for (const sel of eyebrowSelectors) {
            eyebrowEl = heroEl.querySelector(sel);
            if (eyebrowEl) break;
        }
    }
    const eyebrow = eyebrowEl ? {
        fontSize: window.getComputedStyle(eyebrowEl).fontSize,
        letterSpacing: window.getComputedStyle(eyebrowEl).letterSpacing,
        textTransform: window.getComputedStyle(eyebrowEl).textTransform,
    } : null;

    // Sections after hero (first 3)
    const allSections = Array.from(document.querySelectorAll('main section, main > div, [class*="section"]'));
    const contentSections = allSections.slice(1, 4).map(el => ({
        paddingTop: window.getComputedStyle(el).paddingTop,
        paddingBottom: window.getComputedStyle(el).paddingBottom,
        maxWidthInner: (() => {
            const inner = el.querySelector('div, .container, .inner, .wrapper');
            return inner ? window.getComputedStyle(inner).maxWidth : null;
        })(),
        gap: window.getComputedStyle(el).gap,
    }));

    // Buttons / CTAs
    const btnEl = document.querySelector('a[class*="btn"], button[class*="btn"], a[class*="cta"], button[class*="cta"], a[class*="button"], .button, [role="button"]');
    const btn = btnEl ? {
        paddingTop: window.getComputedStyle(btnEl).paddingTop,
        paddingBottom: window.getComputedStyle(btnEl).paddingBottom,
        paddingLeft: window.getComputedStyle(btnEl).paddingLeft,
        paddingRight: window.getComputedStyle(btnEl).paddingRight,
        fontSize: window.getComputedStyle(btnEl).fontSize,
        letterSpacing: window.getComputedStyle(btnEl).letterSpacing,
        textTransform: window.getComputedStyle(btnEl).textTransform,
        borderRadius: window.getComputedStyle(btnEl).borderRadius,
    } : null;

    // Nav
    const navEl = document.querySelector('nav, header nav, [role="navigation"]');
    const nav = navEl ? {
        height: window.getComputedStyle(navEl).height,
        paddingTop: window.getComputedStyle(navEl).paddingTop,
        paddingBottom: window.getComputedStyle(navEl).paddingBottom,
    } : null;
    const navLinkEl = navEl ? navEl.querySelector('a') : null;
    const navLink = navLinkEl ? {
        fontSize: window.getComputedStyle(navLinkEl).fontSize,
        letterSpacing: window.getComputedStyle(navLinkEl).letterSpacing,
        textTransform: window.getComputedStyle(navLinkEl).textTransform,
    } : null;

    // H2
    const h2El = document.querySelector('h2');
    const h2 = h2El ? {
        fontSize: window.getComputedStyle(h2El).fontSize,
        lineHeight: window.getComputedStyle(h2El).lineHeight,
        marginTop: window.getComputedStyle(h2El).marginTop,
        marginBottom: window.getComputedStyle(h2El).marginBottom,
    } : null;

    // Body paragraph in content
    const pEl = document.querySelector('main p, section p, article p');
    const para = pEl ? {
        fontSize: window.getComputedStyle(pEl).fontSize,
        lineHeight: window.getComputedStyle(pEl).lineHeight,
    } : null;

    return { body, hero, h1, eyebrow, contentSections, btn, nav, navLink, h2, para };
}
"""


def extract(page, url, key):
    data = {}
    try:
        page.goto(url, wait_until="domcontentloaded", timeout=45000)
        time.sleep(3)
        # Dismiss cookie banners
        for sel in COOKIE_SELECTORS:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=1000):
                    el.click(timeout=2000)
                    time.sleep(1)
                    break
            except Exception:
                pass
        data = page.evaluate(EXTRACT_JS)
    except PWTimeout:
        print(f"  TIMEOUT for {key}, saving partial")
        try:
            data = page.evaluate(EXTRACT_JS)
        except Exception:
            data = {"error": "timeout_and_eval_failed"}
    except Exception as e:
        data = {"error": str(e)}
    out = f"{OUT_DIR}/{key}.json"
    with open(out, "w") as f:
        json.dump(data, f, indent=2)
    print(f"  Wrote {out}")
    return data


def main():
    with sync_playwright() as p:
        browser = p.firefox.launch(headless=True)
        ctx = browser.new_context(viewport={"width": 1440, "height": 900})
        page = ctx.new_page()
        results = {}
        for key, url in SITES.items():
            print(f"Extracting {key}: {url}")
            results[key] = extract(page, url, key)
        browser.close()
    print("Done. Files:")
    for key in SITES:
        print(f"  {OUT_DIR}/{key}.json")


if __name__ == "__main__":
    main()
