#!/usr/bin/env python3
"""
First time login helper for Phase 2.

Opens the saved Chrome on one site so Steven can log in by hand. The window
stays open while he signs in. When he is done, a small flag file is created
(BidBrain does this when Steven says so) and the browser closes cleanly, saving
the login into the profile so future daily runs do not need him.

Usage:   python3 login.py motorway
Sites:   motorway, carwow, glass, cazana

This never logs in for him and never places a bid. It just opens the page.
"""

import sys
import os
import time
import signal

from playwright.sync_api import sync_playwright
from bidbrain import browser

FLAG = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", ".login_done")

_should_close = {"flag": False}


def _stop(*_):
    _should_close["flag"] = True


def main():
    if len(sys.argv) < 2 or sys.argv[1] not in browser.SITES:
        print("Tell me which site. One of:", ", ".join(browser.SITES))
        sys.exit(1)

    site_key = sys.argv[1]
    site = browser.SITES[site_key]
    # "manual" mode waits for Steven's done flag instead of auto closing on
    # login, so he can apply a saved filter or navigate before we capture.
    manual = len(sys.argv) > 2 and sys.argv[2] == "manual"

    # Clear any stale flag from a previous run.
    if os.path.exists(FLAG):
        os.remove(FLAG)

    # Close cleanly if BidBrain stops this process too.
    signal.signal(signal.SIGTERM, _stop)
    signal.signal(signal.SIGINT, _stop)

    with sync_playwright() as p:
        ctx = browser.open_context(p, headless=False)
        page = ctx.pages[0] if ctx.pages else ctx.new_page()

        # Try the known address, but never crash if it is wrong. The window
        # stays open so Steven can type his usual address into the bar.
        try:
            page.goto(site["login_url"], wait_until="domcontentloaded", timeout=15000)
        except Exception:
            try:
                page.goto("about:blank")
            except Exception:
                pass
            print(f"Could not open {site['login_url']} automatically.")
            print("No problem. In the browser window, type your usual " + site["name"] + " address into the bar and go from there.")

        # If the dealer address bounced us to a marketing page, try to click the
        # Log in control to reach the real sign in form, so Steven sees a login
        # box rather than a marketing page.
        try:
            if "partner" in page.url or "carwow.co.uk/partners" in page.url:
                for sel in ['a:has-text("Log in")', 'a:has-text("Login")',
                            'text=Log in', 'role=link[name=/log ?in/i]']:
                    try:
                        page.click(sel, timeout=2500)
                        page.wait_for_load_state("domcontentloaded", timeout=8000)
                        break
                    except Exception:
                        continue
        except Exception:
            pass

        print(f"\n{site['name']} browser is open.")
        print("Log in as normal, then open the new daily stock page so BidBrain")
        print("can learn the layout. When you are ready, tell BidBrain and it")
        print("will snapshot the page, save the login, and close.\n")

        snap_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "inspect")
        os.makedirs(snap_dir, exist_ok=True)
        status_path = os.path.join(snap_dir, f"{site_key}_status.txt")
        live_path = os.path.join(snap_dir, f"{site_key}_live.png")

        # A per site signal that Steven has reached the logged in dealer area.
        # When seen, capture automatically so there is no "done" to time.
        def logged_in_url(u):
            from urllib.parse import urlparse
            parts = urlparse(u)
            host, path = parts.netloc, parts.path
            if sys.argv[1] == "carwow":
                # Logged in once we are on the dealer host but past the login form.
                return host == "dealers.carwow.co.uk" and "login" not in path
            if sys.argv[1] == "motorway":
                return host == "pro.motorway.co.uk" and "login" not in path
            return False

        # Watch the browser, writing what each tab shows so BidBrain can guide
        # Steven in real time. Stop on the flag, on auto detect, or after a wait.
        waited = 0
        auto = False
        while not _should_close["flag"] and not os.path.exists(FLAG) and waited < 600:
            try:
                lines = [f"tab {i}: {pg.url}" for i, pg in enumerate(ctx.pages)]
            except Exception:
                lines = ["could not read tabs"]
            with open(status_path, "w", encoding="utf-8") as f:
                f.write("\n".join(lines))
            # A live screenshot so BidBrain can see exactly what this window shows.
            try:
                (ctx.pages[-1] if ctx.pages else page).screenshot(path=live_path)
            except Exception:
                pass
            if not manual and any(logged_in_url(pg.url) for pg in ctx.pages):
                auto = True
                break
            time.sleep(2)
            waited += 2
        if auto:
            print("Detected the logged in dealer area, capturing.")

        # Save the full session state so a site whose login cookie does not
        # survive a restart (Carwow) stays logged in for the daily run.
        try:
            from bidbrain import browser as _b
            ctx.storage_state(path=_b.state_path(site_key))
            print(f"Saved session state for {site['name']}.")
        except Exception as e:
            print(f"Could not save session state, {e}")

        # Snapshot whatever page Steven finished on, so the reader can be built
        # against the real layout rather than a guess.
        snap_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "inspect")
        os.makedirs(snap_dir, exist_ok=True)
        site_key = sys.argv[1]
        urls = []
        for idx, pg in enumerate(ctx.pages):
            try:
                url = pg.url
                urls.append(f"tab {idx}: {url}")
                with open(os.path.join(snap_dir, f"{site_key}_tab{idx}.html"), "w", encoding="utf-8") as f:
                    f.write(pg.content())
                pg.screenshot(path=os.path.join(snap_dir, f"{site_key}_tab{idx}.png"), full_page=True)
            except Exception as e:
                urls.append(f"tab {idx}: could not read, {e}")
        with open(os.path.join(snap_dir, f"{site_key}_urls.txt"), "w", encoding="utf-8") as f:
            f.write("\n".join(urls))
        print(f"Snapshot saved {len(ctx.pages)} tab(s) to data/inspect for {site['name']}.")
        for u in urls:
            print("   ", u)

        print(f"Saving the {site['name']} login and closing the browser.")
        ctx.close()

    if os.path.exists(FLAG):
        os.remove(FLAG)


if __name__ == "__main__":
    main()
