"""Load higgsfield.ai/ai/video in CloakBrowser using the user's Chrome cookies.

Stops at the ready state. Does NOT click Generate.

Also writes the READINESS FILE videoclaw checks before it will render Seedance
2.0 free through your Higgsfield account (``<session>/.vclaw-engine-ready.json``).
Only this script writes it, because only this script proves you are signed in:
``bootstrap.sh`` installs dependencies and can say nothing about the session.
The file is rewritten on every run, verdict included, so a stale
``loggedIn: true`` from an earlier import cannot outlive the session it
described.
"""
import json
import os
import sys
from datetime import datetime, timezone

import browser_cookie3
from cloakbrowser import launch_persistent_context

URL = "https://higgsfield.ai/ai/video"
PROFILE_DIR = os.environ.get("HIGGS_VCLAW_PROFILE") or os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".cloak-profile"))
# The login screenshot is a picture of an authenticated account page, so it
# belongs with the rest of the session state in the profile directory — NOT in
# the current working directory, which on the README's own recipe is the
# installed package under node_modules.
SHOT = os.path.join(PROFILE_DIR, "higgsfield_loggedin.png")
CHROME_COOKIE_FILE = os.environ.get("CHROME_COOKIE_FILE") or os.path.expanduser(
    "~/Library/Application Support/Google/Chrome/Profile 1/Cookies"
)
MARKER = os.path.join(PROFILE_DIR, ".vclaw-engine-ready.json")


def cloakbrowser_version():
    try:
        from importlib.metadata import version

        return version("cloakbrowser")
    except Exception:
        return None


def write_marker(logged_in):
    """Record this import's verdict where videoclaw reads it.

    videoclaw renders free only when this file parses and carries
    ``loggedIn: true``. Before it existed, the check accepted the Python
    environment and the session directory merely EXISTING, which an empty
    ``mkdir`` satisfies -- so an unfinished setup reported a working free
    engine.
    """
    with open(MARKER, "w", encoding="utf-8") as handle:
        json.dump(
            {
                "schemaVersion": 1,
                "bootstrappedAt": datetime.now(timezone.utc)
                .isoformat(timespec="seconds")
                .replace("+00:00", "Z"),
                "profileDir": os.path.abspath(PROFILE_DIR),
                "cloakbrowser": cloakbrowser_version(),
                "loggedIn": bool(logged_in),
            },
            handle,
            indent=2,
        )
        handle.write("\n")
    return MARKER


def get_cookies():
    """Pull higgsfield.ai cookies from Chrome Profile 1 -> Playwright format."""
    jar = browser_cookie3.chrome(
        cookie_file=CHROME_COOKIE_FILE, domain_name="higgsfield.ai"
    )
    cookies = []
    for c in jar:
        ck = {
            "name": c.name,
            "value": c.value,
            "domain": c.domain,
            "path": c.path or "/",
            "secure": bool(c.secure),
        }
        if c.expires:
            ck["expires"] = float(c.expires)
        cookies.append(ck)
    return cookies


def main():
    cookies = get_cookies()
    print(f"COOKIES_FOUND: {len(cookies)}")
    for c in cookies:
        print(f"  - {c['name']} ({c['domain']})")
    if not cookies:
        print("NO_COOKIES: none for higgsfield.ai in default Chrome profile.")
        sys.exit(2)

    ctx = launch_persistent_context(PROFILE_DIR, headless=True)
    ctx.add_cookies(cookies)
    page = ctx.new_page()
    page.goto(URL, wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(5000)

    title = page.title()
    final_url = page.url
    nav = ""
    try:
        nav = page.inner_text("header") or page.inner_text("nav")
    except Exception:
        nav = page.inner_text("body")[:400]

    has_login = "Sign up" in nav or "Log in" in nav or "Login" in nav
    logged_in = not has_login

    page.screenshot(path=SHOT, full_page=False)

    print(f"TITLE: {title}")
    print(f"FINAL_URL: {final_url}")
    print(f"LOGGED_IN_HEURISTIC: {logged_in}  (login/signup visible: {has_login})")
    print(f"SCREENSHOT: {SHOT}")
    print("NAV_PREVIEW:")
    print(nav.replace("\n", " | ").strip()[:500])

    ctx.close()

    write_marker(logged_in)
    print(f"MARKER: {MARKER} (loggedIn: {logged_in})")
    if not logged_in:
        print(
            "NOT_SIGNED_IN: the imported session did not reach a signed-in page, so videoclaw "
            "will keep rendering Seedance 2.0 through the paid API. Log in to higgsfield.ai in "
            "Chrome and run this script again."
        )
        sys.exit(3)


if __name__ == "__main__":
    main()
