"""
Fiverr-Assistent: Browser mit gespeichertem Profil, Seiten öffnen, Texte einfügen.

Nutzt Playwright (persistentes Profil = du bleibst eingeloggt).
Jam kann Fiverr-Formulare nicht zu 100 % ausfüllen (Fiverr ändert oft das Layout) –
aber: Verkäufer-Ansicht, Gig-Editor, Zwischenablage einfügen, Profil-Seite.
"""

from __future__ import annotations

import random
import re
import time
from pathlib import Path

from jam.brain import JamBrain, JamState
from jam.fiverr_connect import (
    DEFAULT_USERNAME,
    get_username,
    manage_gigs_url,
    new_gig_url,
    seller_urls,
)
from jam.owner import owner_name
from jam.paypal_donate import PAYPAL_EMAIL

PROFILE_DIR = Path(__file__).resolve().parent.parent / "data" / "fiverr-playwright-profile"
GIG_TEXT_FILE = Path(__file__).resolve().parent.parent / "data" / "fiverr_last_gig_clip.txt"

PROFILE_EDIT_URL = "https://www.fiverr.com/users/{user}/edit/details"
SELLER_HOME = "https://www.fiverr.com/seller_dashboard"


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

        return True
    except ImportError:
        return False


def hears_auto_setup(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if "fiverr" not in h and "fiver" not in h:
        return False
    return any(
        w in h
        for w in (
            "automatisch",
            "selber anlegen",
            "selbst anlegen",
            "eintragen",
            "ausfüllen",
            "ausfuellen",
            "übernimm",
            "uebernimm",
            "website zugreif",
            "formular",
            "einrichten",
            "anlegen",
            "trage",
            "eintragen",
            "selber ein",
            "selbst ein",
        )
    )


def _parse_gig_fields(text: str) -> dict:
    title_m = re.search(
        r"(?:TITEL|Title).*?:\s*(.+?)(?:\n\n|\nKATEGORIE|\nBeschreibung|$)",
        text,
        re.I | re.S,
    )
    title = (title_m.group(1).strip().split("\n")[0] if title_m else "").strip()
    if not title:
        m = re.search(r"^Titel:\s*(.+)$", text, re.I | re.M)
        title = m.group(1).strip() if m else "Python & Web Hilfe (schnell)"
    desc_m = re.search(
        r"(?:BESCHREIBUNG|Beschreibung):\s*(.+?)(?:\n\n(?:💳|PAKETE|PayPal|LIEFER)|\Z)",
        text,
        re.I | re.S,
    )
    description = desc_m.group(1).strip() if desc_m else text[:2000]
    price_m = re.search(
        r"(?:Standard|Preis|price).*?(\d+(?:[.,]\d+)?)\s*(?:EUR|€)",
        text,
        re.I,
    )
    price = 39.0
    if price_m:
        try:
            price = float(price_m.group(1).replace(",", "."))
        except ValueError:
            pass
    if price < 5:
        price = 39.0
    tags_m = re.search(r"TAGS:\s*(.+)$", text, re.I | re.M)
    tags = tags_m.group(1).strip() if tags_m else "python, web, deutsch, script"
    return {
        "title": title[:80],
        "description": description[:2500],
        "price": int(price) if price == int(price) else price,
        "tags": tags[:500],
    }


def _latest_gig_text(brain: JamBrain) -> str:
    from jam.urgent_offers import OFFERS_ROOT
    from jam.sales_engine import SALES_ROOT

    forced = GIG_TEXT_FILE.read_text(encoding="utf-8", errors="replace") if GIG_TEXT_FILE.is_file() else ""
    if forced and "python" in forced.lower() and len(forced) > 80:
        return forced[:8000]

    best: tuple[int, str] | None = None
    for root in (SALES_ROOT, OFFERS_ROOT, Path.home() / "Documents" / "Jam-Cursor-Business"):
        if not root.is_dir():
            continue
        dirs = sorted(
            root.iterdir(),
            key=lambda p: p.stat().st_mtime if p.is_dir() else 0,
            reverse=True,
        )
        for d in dirs[:20]:
            if not d.is_dir():
                continue
            if "cent" in d.name.lower() or "wallpaper-cent" in d.name.lower():
                continue
            gig = d / "FIVERR_GIG.txt"
            if not gig.is_file():
                continue
            raw = gig.read_text(encoding="utf-8", errors="replace")[:8000]
            fields = _parse_gig_fields(raw)
            score = 0
            if "python-mini-tool" in d.name.lower():
                score += 100
            if fields["price"] >= 15 and fields["price"] <= 99:
                score += int(fields["price"])
            if "python" in raw.lower():
                score += 30
            if "one-page" in d.name.lower() or "webseite" in d.name.lower():
                score += 10
            if best is None or score > best[0]:
                best = (score, raw)
    if best:
        return best[1]
    if GIG_TEXT_FILE.is_file():
        return GIG_TEXT_FILE.read_text(encoding="utf-8", errors="replace")[:8000]
    owner = owner_name(brain.state)
    return (
        f"I will deliver fast Python/Web help for {owner}.\n"
        f"PayPal: {PAYPAL_EMAIL}\n"
        f"Message me before ordering – built with Cursor.\n"
    )


def _save_gig_clip(text: str) -> None:
    GIG_TEXT_FILE.parent.mkdir(parents=True, exist_ok=True)
    GIG_TEXT_FILE.write_text(text, encoding="utf-8")


def _paste_clipboard_win(text: str) -> bool:
    try:
        import subprocess
        import tempfile

        with tempfile.NamedTemporaryFile(
            mode="w", encoding="utf-8", suffix=".txt", delete=False
        ) as tmp:
            tmp.write(text[:12000])
            tmp_path = tmp.name.replace("'", "''")
        subprocess.run(
            [
                "powershell",
                "-NoProfile",
                "-Command",
                f"Get-Content -Raw -LiteralPath '{tmp_path}' -Encoding UTF8 | Set-Clipboard",
            ],
            check=True,
            timeout=12,
            capture_output=True,
        )
        return True
    except Exception:
        return False


def _type_slow(page, text: str) -> None:
    try:
        page.keyboard.type(text[:200], delay=15)
    except Exception:
        pass


def _fill_gig_wizard(page, fields: dict) -> list[str]:
    """Fiverr Gig-Wizard: Titel, Kategorie-Hinweis, Beschreibung, Preis – best effort."""
    done: list[str] = []
    title = fields["title"]
    desc = (
        f"{fields['description']}\n\n"
        f"✅ Fast delivery | German & English\n"
        f"💳 PayPal: {PAYPAL_EMAIL}\n"
        f"Built with Cursor for professional results.\n"
    )
    price = str(fields["price"])

    # „Gig erstellen“ / Create
    _try_click_text(
        page,
        "Create a new Gig",
        "Neues Gig",
        "Gig erstellen",
        "Create Gig",
    )
    page.wait_for_timeout(1500)

    # Titel – viele mögliche Selektoren
    title_filled = False
    for attempt in (
        lambda: page.get_by_placeholder(re.compile(r"gig title|titel|title", re.I)).first,
        lambda: page.locator('input[name*="title" i]').first,
        lambda: page.locator("[data-testid*='title']").first,
        lambda: page.locator("input[type='text']").first,
    ):
        try:
            el = attempt()
            if el.is_visible(timeout=2000):
                el.click(timeout=3000)
                el.fill("")
                el.fill(title)
                title_filled = True
                done.append("Titel")
                break
        except Exception:
            continue
    if not title_filled:
        try:
            if not page.is_closed():
                page.locator("input[type='text']").first.click(timeout=2000)
                page.keyboard.press("Control+a")
                _type_slow(page, title)
                done.append("Titel getippt")
        except Exception:
            pass

    page.wait_for_timeout(800)

    # Kategorie: Programmierung
    for cat in (
        "Programmierung",
        "Programming",
        "Programmierung & Technik",
        "Programming & Tech",
        "Website",
        "Python",
    ):
        if _try_click_text(page, cat):
            done.append("Kategorie")
            page.wait_for_timeout(600)
            break

    # Weiter / Continue zwischen Schritten
    for _ in range(4):
        clicked = _try_click_text(
            page,
            "Weiter",
            "Continue",
            "Save & Continue",
            "Speichern",
            "Save & continue",
            "Überspringen",
            "Skip",
        )
        if clicked:
            page.wait_for_timeout(2000)
        else:
            break

    # Beschreibung – größtes Textfeld
    desc_filled = 0
    try:
        areas = page.locator("textarea")
        n = areas.count()
        best_i = 0
        best_len = 0
        for i in range(min(n, 10)):
            try:
                t = areas.nth(i)
                if t.is_visible():
                    box = t.bounding_box() or {}
                    h = box.get("height", 0) or 0
                    if h > best_len:
                        best_len = h
                        best_i = i
            except Exception:
                pass
        if n > 0:
            t = areas.nth(best_i)
            t.click(timeout=3000)
            t.fill(desc)
            desc_filled = 1
            done.append("Beschreibung")
    except Exception:
        pass

    if not desc_filled:
        try:
            ed = page.locator("[contenteditable='true']").first
            ed.click(timeout=3000)
            ed.fill(desc)
            done.append("Beschreibung (rich)")
        except Exception:
            page.keyboard.press("Control+v")
            done.append("Beschreibung Strg+V")

    # Preis-Felder
    for sel in (
        'input[name*="price" i]',
        'input[type="number"]',
        'input[placeholder*="price" i]',
        'input[placeholder*="preis" i]',
    ):
        try:
            loc = page.locator(sel)
            for i in range(min(loc.count(), 5)):
                el = loc.nth(i)
                if el.is_visible():
                    el.fill(price)
                    done.append(f"Preis {price}")
                    break
        except Exception:
            continue

    # Tags
    for tag in fields["tags"].split(",")[:5]:
        t = tag.strip()
        if not t:
            continue
        try:
            page.get_by_placeholder(re.compile("tag", re.I)).first.fill(t)
            page.keyboard.press("Enter")
        except Exception:
            break
    if "tag" not in " ".join(done).lower():
        try:
            page.locator('input[placeholder*="tag" i]').first.fill(fields["tags"][:80])
            done.append("Tags")
        except Exception:
            pass

    page.wait_for_timeout(1000)
    _try_click_text(page, "Weiter", "Continue", "Save & Continue", "Speichern")
    return done


def _try_fill_textareas(page, text: str) -> int:
    """Füllt sichtbare Textfelder – best effort."""
    filled = 0
    chunk = text[:4000]
    selectors = (
        "textarea",
        "[contenteditable='true']",
        "input[type='text']",
    )
    for sel in selectors:
        try:
            loc = page.locator(sel)
            n = min(loc.count(), 6)
            for i in range(n):
                el = loc.nth(i)
                if not el.is_visible():
                    continue
                try:
                    el.click(timeout=2000)
                    el.fill(chunk[:500] if sel != "textarea" else chunk[:2500])
                    filled += 1
                except Exception:
                    try:
                        el.press("Control+a")
                        el.press("Control+v")
                        filled += 1
                    except Exception:
                        pass
        except Exception:
            continue
    return filled


def _try_click_text(page, *labels: str) -> bool:
    for label in labels:
        try:
            page.get_by_role("button", name=re.compile(label, re.I)).first.click(timeout=4000)
            return True
        except Exception:
            pass
        try:
            page.get_by_role("link", name=re.compile(label, re.I)).first.click(timeout=4000)
            return True
        except Exception:
            pass
        try:
            page.get_by_text(re.compile(label, re.I)).first.click(timeout=3000)
            return True
        except Exception:
            pass
    return False


def _attempt_publish_gig(page) -> list[str]:
    """Alle Wizard-Schritte durchklicken inkl. Publish."""
    done: list[str] = []
    publish_labels = (
        "Publish",
        "Veröffentlichen",
        "Publish Gig",
        "Save & Publish",
        "Save and publish",
        "Submit",
        "Create Gig",
        "Go live",
        "I agree",
        "Agree and publish",
        "Confirm",
        "Yes, publish",
        "Publish Now",
        "Save & Continue",
        "Weiter",
        "Continue",
        "Next",
    )
    for _ in range(10):
        for label in publish_labels:
            if _try_click_text(page, label):
                done.append(label)
                page.wait_for_timeout(2200)
    return done


def run_fiverr_assist(
    brain: JamBrain,
    *,
    mode: str = "gig",
    user_initiated: bool = True,
    try_publish: bool = False,
) -> str:
    """
    Playwright: persistentes Browser-Profil, Fiverr Seller + Gig-Editor.
    mode: gig | profile | full
    """
    if not _playwright_ok():
        return (
            "Für Auto-Fiverr brauchst du einmal: "
            "pip install playwright && playwright install msedge "
            "(oder chromium). Dann nochmal „Jam, Fiverr automatisch“."
        )

    from playwright.sync_api import sync_playwright

    owner = owner_name(brain.state)
    user = get_username(brain.state) or DEFAULT_USERNAME
    gig_text = _latest_gig_text(brain)
    fields = _parse_gig_fields(gig_text)
    _save_gig_clip(gig_text)
    _paste_clipboard_win(fields["description"])

    PROFILE_DIR.mkdir(parents=True, exist_ok=True)
    steps_done: list[str] = []

    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(SELLER_HOME, wait_until="domcontentloaded", timeout=60_000)
            page.wait_for_timeout(2500)
            steps_done.append("Seller-Dashboard")

            _try_click_text(
                page,
                "Zur Verkaufsansicht",
                "Selling",
                "Verkaufen",
                "Seller",
            )
            page.wait_for_timeout(1500)

            if mode in ("profile", "full"):
                try:
                    page.goto(
                        PROFILE_EDIT_URL.format(user=user),
                        wait_until="domcontentloaded",
                        timeout=45_000,
                    )
                    page.wait_for_timeout(2000)
                    bio = (
                        f"Ich liefere schnelle Python- und Web-Hilfe für {owner}. "
                        f"Kleine Aufträge, klare Preise, PayPal {PAYPAL_EMAIL}. "
                        f"Deutsch & English."
                    )
                    n = _try_fill_textareas(page, bio)
                    steps_done.append(f"Profil ({n} Felder)")
                except Exception:
                    steps_done.append("Profil übersprungen")
                page.wait_for_timeout(1000)

            if mode in ("gig", "full"):
                page.goto(manage_gigs_url(user), wait_until="domcontentloaded", timeout=60_000)
                page.wait_for_timeout(2500)
                _try_click_text(page, "Create a new Gig", "Neues Gig", "Gig erstellen")
                page.wait_for_timeout(1500)
                page.goto(new_gig_url(user), wait_until="domcontentloaded", timeout=60_000)
                page.wait_for_timeout(4000)
                steps_done.append("Gig-Editor")
                wizard_steps = _fill_gig_wizard(page, fields)
                steps_done.extend(wizard_steps)

                if try_publish:
                    creds = None
                    try:
                        from jam.platform_auth import load_credentials

                        creds = load_credentials()
                    except Exception:
                        pass
                    if creds:
                        try:
                            from jam.platform_auth import _fill_login_form

                            _fill_login_form(page, creds[0], creds[1])
                            steps_done.append("Login")
                        except Exception:
                            pass
                    pub_steps = _attempt_publish_gig(page)
                    steps_done.extend(pub_steps[:8] or ["Publish-Versuch"])

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

            page.wait_for_timeout(3000)
            if user_initiated:
                page.bring_to_front()

            brain.state.fiverr_assist_count = getattr(brain.state, "fiverr_assist_count", 0) + 1
            brain.state.last_fiverr_assist_at = time.time()
            brain.state.last_action = "fiverr_assist"
            if try_publish:
                brain.state.fiverr_publish_attempted = True
                brain.state.remember("Fiverr Publish-Versuch durch Jam")
            else:
                brain.state.remember("Fiverr-Assistent: Browser + Text eingefügt")
            brain.save()

            pub_bit = (
                " Ich habe **Publish** geklickt (soweit Fiverr es erlaubt)."
                if try_publish
                else " Bitte **Veröffentlichen** im Browser – oder sag „Jam veröffentlichen“."
            )
            return (
                f"{owner}, Gig **{fields['title']}** – {fields['price']} €. "
                f"Schritte: {', '.join(steps_done)}.{pub_bit} "
                f"Screenshot: data/fiverr-last-screen.png"
            )[:520]

    except Exception as e:
        return (
            f"Fiverr-Assistent: {e} – "
            f"Öffne manuell: {new_gig_url(user)} und Strg+V. "
            f"Text liegt in data/fiverr_last_gig_clip.txt"
        )[:480]


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_auto_setup(heard):
        return None
    mode = "full"
    if "profil" in heard.lower():
        mode = "profile"
    elif "gig" in heard.lower():
        mode = "gig"
    return run_fiverr_assist(brain, mode=mode, user_initiated=True)
