"""Freelancer.com – Profil & Skills (David ist eingeloggt)."""

from __future__ import annotations

import json
import random
import re
import time
import webbrowser
from pathlib import Path

from jam.brain import JamBrain, JamState
from jam.owner import owner_name
from jam.paypal_donate import PAYPAL_EMAIL

CONFIG_PATH = Path(__file__).resolve().parent.parent / "data" / "freelancer_config.json"
FREELANCER_ROOT = Path.home() / "Documents" / "Jam-Freelancer"

SKILLS_URL = "https://www.freelancer.com/new-freelancer/skills"
DASHBOARD_URL = "https://www.freelancer.com/dashboard"
BROWSE_PROJECTS = "https://www.freelancer.com/search/projects"
PROFILE_SETTINGS = "https://www.freelancer.com/freelancers/settings/profile"

DEFAULT_SKILLS: tuple[str, ...] = (
    "Python",
    "Web Development",
    "JavaScript",
    "HTML",
    "CSS",
    "API Integration",
    "Automation",
    "Scripting",
    "WordPress",
    "Data Processing",
    "Web Scraping",
    "PHP",
)

CONNECT_LINES = (
    "{owner}, Freelancer ist verbunden! Ich lege jetzt **Skills & Profil** an – du bist schon eingeloggt!",
    "Freelancer aktiv! Skills-Seite ist offen – Texte in der Zwischenablage, PayPal {paypal}.",
)


def _load_cfg() -> dict:
    try:
        if CONFIG_PATH.is_file():
            return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        pass
    return {}


def is_connected(state: JamState) -> bool:
    return bool(getattr(state, "freelancer_connected", False))


def hears_freelancer(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    return "freelancer" in h or "freelancer.com" in h


def hears_logged_in_go(text: str) -> bool:
    low = text.lower()
    if "new-freelancer/skills" in low or "freelancer.com/new" in low:
        return True
    if not hears_freelancer(text):
        if "freelancer.com" not in low and "new-freelancer" not in low:
            return False
    h = text.lower()
    return any(
        w in h
        for w in (
            "angemeldet",
            "eingeloggt",
            "bin drin",
            "login fertig",
            "loslegen",
            "los legen",
            "skills",
            "kannst du",
            "mach weiter",
            "jetzt",
        )
    )


def _profile_text(owner: str) -> dict[str, str]:
    clip = Path(__file__).resolve().parent.parent / "data" / "fiverr_last_gig_clip.txt"
    desc = ""
    if clip.is_file():
        desc = clip.read_text(encoding="utf-8", errors="replace")[:1500]
    headline = "Python & Web Developer | Schnelle Lieferung | DE/EN"
    bio = (
        f"Ich bin {owner}s Entwickler-Partner (Jam/Cursor) – Python, Mini-Tools, "
        f"Webseiten und Scripts. Klare Preise, schnelle Umsetzung.\n\n"
        f"PayPal: {PAYPAL_EMAIL}\n\n"
        f"Leistungen:\n"
        f"- Python Scripts & Automatisierung\n"
        f"- Kleine Webseiten & Landing Pages\n"
        f"- Bugfixes & kleine Features\n"
        f"- HTML/CSS/JS\n\n"
        f"{desc[:800] if desc else ''}"
    ).strip()[:2000]
    return {"headline": headline, "bio": bio}


def write_freelancer_pack(brain: JamBrain) -> Path:
    owner = owner_name(brain.state)
    prof = _profile_text(owner)
    FREELANCER_ROOT.mkdir(parents=True, exist_ok=True)

    skills_block = "\n".join(f"  [ ] {s}" for s in DEFAULT_SKILLS)
    text = f"""FREELANCER – SKILLS & PROFIL ({owner})
========================================
Stand: {time.strftime('%d.%m.%Y %H:%M')}

SEITE (du bist eingeloggt):
{SKILLS_URL}

SKILLS ANWÄHLEN (alle die angeboten werden):
{skills_block}

ÜBERSCHRIFT / HEADLINE:
{prof['headline']}

KURZ-BIO (Profil):
{prof['bio']}

NÄCHSTE SCHRITTE:
1. Skills auf der Seite anklicken / suchen -> Weiter
2. Profil ausfüllen: {PROFILE_SETTINGS}
3. Projekte suchen: {BROWSE_PROJECTS}
4. PayPal in Zahlungen: {PAYPAL_EMAIL}

Dashboard: {DASHBOARD_URL}
"""
    (FREELANCER_ROOT / "SKILLS_UND_PROFIL.txt").write_text(text, encoding="utf-8")
    (FREELANCER_ROOT / "FREELANCER_BIO.txt").write_text(prof["bio"], encoding="utf-8")
    (FREELANCER_ROOT / "SKILLS_LISTE.txt").write_text(
        "\n".join(DEFAULT_SKILLS), encoding="utf-8"
    )
    return FREELANCER_ROOT


def connect_freelancer(brain: JamBrain, *, user_asked: bool = True) -> None:
    state = brain.state
    state.freelancer_connected = True
    state.freelancer_connected_at = time.time()
    state.last_action = "freelancer_connect"
    cfg = _load_cfg()
    cfg["connected_at"] = time.time()
    CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
    CONFIG_PATH.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
    if user_asked:
        state.remember("Freelancer verbunden – Skills-Setup")
    brain.save()


def run_freelancer_setup(brain: JamBrain, *, user_initiated: bool = True) -> str:
    """Skills-Seite + Texte + optional Playwright-Assistent."""
    from jam.active_sell import mark_logged_in

    owner = owner_name(brain.state)
    connect_freelancer(brain, user_asked=user_initiated)
    mark_logged_in(brain)

    folder = write_freelancer_pack(brain)
    prof = _profile_text(owner)
    clip_text = (
        f"Skills: {', '.join(DEFAULT_SKILLS[:8])}\n\n"
        f"Headline: {prof['headline']}\n\n"
        f"{prof['bio']}"
    )
    clip_ok = False
    try:
        from jam.auto_ops import clipboard_text

        clip_ok = clipboard_text(clip_text[:6000])
    except Exception:
        pass

    opened: list[str] = []
    try:
        webbrowser.open(SKILLS_URL, new=2)
        opened.append("Skills")
    except OSError:
        pass

    assist_msg = ""
    try:
        from jam.freelancer_assist import run_freelancer_assist

        assist_msg = run_freelancer_assist(brain, user_initiated=user_initiated)[:280]
    except Exception as e:
        assist_msg = f"Browser-Assistent: {e}"[:120]

    try:
        import os
        import subprocess

        if os.name == "nt":
            subprocess.run(["explorer", str(folder)], check=False, timeout=5)
    except Exception:
        pass

    brain.add_xp(10)
    brain.save()

    clip_bit = "Text in Zwischenablage!" if clip_ok else f"Texte in {folder.name}."
    return (
        random.choice(CONNECT_LINES).format(owner=owner, paypal=PAYPAL_EMAIL)
        + f" Geoeffnet: {', '.join(opened)}. {clip_bit} "
        f"Skills-Seite: {SKILLS_URL} – Skills anklicken, dann Weiter. "
        f"{assist_msg}"
    )[:680]


def platform_entry(state: JamState) -> tuple[str, str]:
    if is_connected(state):
        return ("Freelancer Skills", SKILLS_URL)
    return ("Freelancer", "https://www.freelancer.com/signup")


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_logged_in_go(heard):
        return run_freelancer_setup(brain, user_initiated=True)
    if hears_freelancer(heard) and any(
        w in heard.lower()
        for w in ("verbind", "connect", "einricht", "skills", "profil", "setup")
    ):
        return run_freelancer_setup(brain, user_initiated=True)
    return None
