"""
Freelancer Playwright-Assistent – Skills-Seite ausfüllen (eingeloggt im Profil).

Persistentes Edge-Profil: einmal einloggen, dann bleibt die Session.
Wenn du schon im normalen Browser eingeloggt bist, nutze parallel die
geoeffnete Skills-Seite dort + Zwischenablage aus freelancer_connect.
"""

from __future__ import annotations

import re
import time
from pathlib import Path

from jam.brain import JamBrain
from jam.freelancer_connect import DEFAULT_SKILLS, SKILLS_URL, _profile_text
from jam.owner import owner_name

PROFILE_DIR = Path(__file__).resolve().parent.parent / "data" / "freelancer-playwright-profile"


def _playwright_ok() -> bool:
    try:
        import playwright  # noqa: F401

        return True
    except ImportError:
        return False


def _try_click_text(page, *labels: str) -> bool:
    for label in labels:
        try:
            loc = page.get_by_text(re.compile(re.escape(label), re.I)).first
            if loc.is_visible(timeout=1200):
                loc.click(timeout=4000)
                page.wait_for_timeout(800)
                return True
        except Exception:
            pass
        try:
            btn = page.get_by_role("button", name=re.compile(label, re.I)).first
            if btn.is_visible(timeout=800):
                btn.click(timeout=4000)
                page.wait_for_timeout(800)
                return True
        except Exception:
            pass
    return False


def _add_skill(page, skill: str) -> bool:
    """Skill suchen und hinzufuegen."""
    try:
        search = page.locator(
            'input[type="search"], input[placeholder*="kill" i], input[placeholder*="earch" i]'
        ).first
        if search.is_visible(timeout=1500):
            search.fill(skill, timeout=5000)
            page.wait_for_timeout(600)
    except Exception:
        pass

    if _try_click_text(page, skill):
        return True

    try:
        chip = page.locator(f'[data-skill*="{skill}" i], .skill, .tag').filter(has_text=skill).first
        if chip.is_visible(timeout=1000):
            chip.click(timeout=3000)
            return True
    except Exception:
        pass

    return _try_click_text(page, skill.split()[0])


def run_freelancer_assist(brain: JamBrain, *, user_initiated: bool = True) -> str:
    if not _playwright_ok():
        return "Playwright fehlt – nutze die schon offene Skills-Seite + Zwischenablage."

    from playwright.sync_api import sync_playwright

    owner = owner_name(brain.state)
    prof = _profile_text(owner)
    steps: list[str] = []
    PROFILE_DIR.mkdir(parents=True, exist_ok=True)

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

            page = context.pages[0] if context.pages else context.new_page()
            page.goto(SKILLS_URL, wait_until="domcontentloaded", timeout=90_000)
            page.wait_for_timeout(3000)
            steps.append("Skills-Seite")

            if "login" in page.url.lower() or page.locator('input[type="password"]').count() > 0:
                steps.append("Bitte einloggen im Edge-Fenster")
                if user_initiated:
                    page.bring_to_front()
                page.wait_for_timeout(12_000)

            added = 0
            for skill in DEFAULT_SKILLS[:10]:
                if _add_skill(page, skill):
                    added += 1
                    page.wait_for_timeout(400)
            steps.append(f"{added} Skills")

            for btn in ("Continue", "Weiter", "Next", "Save", "Done", "Fertig"):
                if _try_click_text(page, btn):
                    steps.append(btn)
                    page.wait_for_timeout(2000)
                    break

            for sel in (
                'textarea[name*="description" i]',
                'textarea[id*="bio" i]',
                "textarea",
                'input[name*="headline" i]',
                'input[placeholder*="headline" i]',
            ):
                try:
                    loc = page.locator(sel).first
                    if loc.is_visible(timeout=1000):
                        if "headline" in sel.lower() or "headline" in (
                            loc.get_attribute("placeholder") or ""
                        ).lower():
                            loc.fill(prof["headline"][:120], timeout=5000)
                            steps.append("Headline")
                        else:
                            loc.fill(prof["bio"][:2000], timeout=5000)
                            steps.append("Bio")
                        break
                except Exception:
                    continue

            try:
                shot = Path(__file__).resolve().parent.parent / "data" / "freelancer-last-screen.png"
                page.screenshot(path=str(shot), full_page=False)
                steps.append("Screenshot")
            except Exception:
                pass

            if user_initiated:
                page.bring_to_front()
            page.wait_for_timeout(4000)
            context.close()

        brain.state.freelancer_assist_count = getattr(brain.state, "freelancer_assist_count", 0) + 1
        brain.state.last_freelancer_assist_at = time.time()
        brain.save()

        return (
            f"{owner}, Freelancer-Assistent: {', '.join(steps)}. "
            f"Pruefe Edge-Fenster – Skills anklicken & Weiter. "
            f"Falls Login: einmal anmelden, dann nochmal Jam Freelancer sagen."
        )[:400]

    except Exception as e:
        return f"Freelancer-Assistent: {e} – Skills-URL bleibt offen, Strg+V fuer Texte."[:350]
