"""
Jam-Edge-Fenster öffnen – ein Browser-Profil für Login (Gmail, Fiverr, Gumroad, …).
"""

from __future__ import annotations

import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
HELPER_HTML = ROOT / "data" / "jam_edge_start.html"

PROFILES: dict[str, Path] = {
    "kontakt": ROOT / "data" / "customer-contact-playwright-profile",
    "fiverr": ROOT / "data" / "fiverr-playwright-profile",
    "gumroad": ROOT / "data" / "gumroad-playwright-profile",
    "plattform": ROOT / "data" / "platform-playwright-profile",
    "freelancer": ROOT / "data" / "freelancer-playwright-profile",
}

DEFAULT_PROFILE = "kontakt"

START_LINKS = (
    ("Gmail Login", "https://mail.google.com/"),
    ("Fiverr Seller", "https://www.fiverr.com/seller_dashboard"),
    ("Gumroad Neu", "https://gumroad.com/products/new"),
    ("Freelancer Jobs", "https://www.freelancer.com/job-search/python/"),
    ("Upwork Jobs", "https://www.upwork.com/nx/search/jobs/?q=python"),
    ("Reddit forhire", "https://www.reddit.com/r/forhire/new/"),
)


def _write_helper() -> Path:
    rows = "\n".join(
        f'<li><a href="{url}" target="_blank">{name}</a></li>' for name, url in START_LINKS
    )
    HELPER_HTML.parent.mkdir(parents=True, exist_ok=True)
    HELPER_HTML.write_text(
        f"""<!DOCTYPE html><html lang="de"><head><meta charset="utf-8">
<title>Jam Edge – Login</title>
<style>body{{font-family:system-ui;max-width:640px;margin:2rem auto;padding:1rem}}
h1{{color:#1565c0}} a{{font-size:1.1rem}}</style></head><body>
<h1>Jam-Edge – hier einloggen</h1>
<p>Einmal anmelden – Jam nutzt dieses Profil für Fiverr, Gmail, Bewerbungen.</p>
<ul>{rows}</ul>
<p><small>Fenster offen lassen. Jam arbeitet im Hintergrund weiter.</small></p>
</body></html>""",
        encoding="utf-8",
    )
    return HELPER_HTML


def open_jam_edge(*, profile: str = DEFAULT_PROFILE, keep_open_minutes: float = 120.0) -> str:
    """Edge mit Jam-Profil öffnen und vorn halten."""
    if profile not in PROFILES:
        profile = DEFAULT_PROFILE
    prof_dir = PROFILES[profile]
    prof_dir.mkdir(parents=True, exist_ok=True)

    try:
        import playwright  # noqa: F401
    except ImportError:
        return "Playwright fehlt: pip install playwright && playwright install msedge"

    from playwright.sync_api import sync_playwright

    helper = _write_helper()
    steps = [f"Profil: {profile}"]

    with sync_playwright() as p:
        try:
            context = p.chromium.launch_persistent_context(
                str(prof_dir),
                channel="msedge",
                headless=False,
                viewport={"width": 1400, "height": 900},
                locale="de-DE",
            )
        except Exception:
            context = p.chromium.launch_persistent_context(
                str(prof_dir),
                headless=False,
                viewport={"width": 1400, "height": 900},
            )

        page = context.pages[0] if context.pages else context.new_page()
        page.goto(helper.as_uri(), wait_until="domcontentloaded", timeout=60_000)
        steps.append("Startseite")
        for name, url in START_LINKS[:3]:
            try:
                p2 = context.new_page()
                p2.goto(url, wait_until="domcontentloaded", timeout=45_000)
                steps.append(name)
                time.sleep(0.5)
            except Exception:
                pass
        try:
            page.bring_to_front()
        except Exception:
            pass
        ms = int(keep_open_minutes * 60_000)
        try:
            page.wait_for_timeout(min(ms, 7_200_000))
        except Exception:
            pass

    return f"Jam-Edge ({profile}) war offen: {', '.join(steps)}. Profil-Ordner: {prof_dir.name}"


def open_jam_edge_quick() -> str:
    """Jam Browser (eigenes Fenster) – blockiert nicht, Logins im Profil."""
    try:
        from jam.jam_browser import open_jam_browser_quick

        return open_jam_browser_quick()
    except Exception:
        return open_jam_edge(profile=DEFAULT_PROFILE, keep_open_minutes=120.0)
