"""Jam lernt Cursor + Geld verdienen, baut Produkte und sucht Käufer (legal, mit Internet)."""

from __future__ import annotations

import random
import re
import time
import webbrowser
from datetime import datetime
from pathlib import Path
from urllib.parse import quote_plus

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

BUSINESS_ROOT = Path.home() / "Documents" / "Jam-Cursor-Business"
AUTO_GAP_SEC = 150.0
USER_GAP_SEC = 50.0
MAX_PER_HOUR = 3

KI_STUDIO_URL = "https://www.ki-web-studio.de/"

PRODUCTS: dict[str, dict] = {
    "desktop_helper": {
        "title": "Jam Desktop-Helfer (Python)",
        "price": (19, 49),
        "files": {
            "main.py": (
                '#!/usr/bin/env python3\n"""Kleines Tool – von Jam in Cursor gebaut."""\n\n'
                "import datetime\n\n"
                "def greet(name: str = 'Welt') -> str:\n"
                "    return f'Hallo {name}! Jam-Tool – {datetime.date.today()}'\n\n"
                "if __name__ == '__main__':\n"
                "    print(greet())\n"
                "    print('Tipp: In Cursor weiter ausbauen!')\n"
            ),
        },
    },
    "landing_ki": {
        "title": "Mini-Webseite „Code von David“",
        "price": (49, 199),
        "html": True,
    },
    "quote_bot": {
        "title": "Zitat-Generator Script",
        "price": (9, 29),
        "files": {
            "quotes.py": (
                '"""Zufalls-Zitate – Jam Produkt."""\nimport random\n\n'
                "ZITATE = [\n"
                '    "Code ist Poesie – Jam",\n'
                '    "Cursor macht mich schlau!",\n'
                '    "David programmiert alles!",\n'
                "]\n\n"
                "if __name__ == '__main__':\n"
                "    print(random.choice(ZITATE))\n"
            ),
        },
    },
}

BUYER_SEARCHES = (
    "freelancer python kleinprojekt deutsch",
    "fiverr python script kaufen",
    "upwork deutsch webentwicklung",
    "kleinanzeigen programmierer gesucht",
    "reddit forhire python",
)

SIMULATED_BUYERS = (
    ("TechStart Mia", "braucht kleines Python-Script", "Budget ~40 €"),
    ("Blogger Tom", "will Landingpage", "Budget ~120 €"),
    ("Shop Lena", "sucht Automatisierung", "Budget ~80 €"),
    ("GameDev Kai", "Mini-Tool gesucht", "Budget ~25 €"),
    ("Verein Plus", "Homepage Update", "Budget ~150 €"),
)

LINES = (
    "{owner}, ich lerne Cursor + Geld verdienen – und baue was zum Verkauf!",
    "Business-Jam: Cursor-Projekt fertig, Käufer-Suche läuft!",
    "Ich programmiere in Cursor und suche Käufer für dich, {owner}!",
)

CURSOR_LEARN_TOPICS = (
    "Cursor IDE tutorial deutsch",
    "mit programmieren geld verdienen anfänger",
    "freelance python cursor editor",
)


def hears_cursor_business(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    has_cursor = "cursor" in h
    has_money = any(w in h for w in ("geld", "verdien", "verkauf", "käufer", "kaeufer", "kunde"))
    has_code = any(w in h for w in ("programmier", "code", "entwickl"))
    if has_cursor and (has_money or has_code):
        return True
    if has_code and has_money and any(w in h for w in ("lern", "such", "käufer", "verkauf")):
        return True
    if "käufer suchen" in h or "kaeufer suchen" in h:
        return True
    if "cursor" in h and "lern" in h:
        return True
    return False


def _sessions_last_hour(state: JamState) -> int:
    cutoff = time.time() - 3600
    log = getattr(state, "cursor_business_log", []) or []
    return sum(1 for e in log if isinstance(e, dict) and e.get("at", 0) > cutoff)


def can_run(state: JamState, *, user: bool = False) -> tuple[bool, str]:
    if state.stage < 2:
        return False, "Ab Stufe 2 kann ich Cursor-Business – ich wachse noch!"
    gap = USER_GAP_SEC if user else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_cursor_business_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_cursor_business_at))
        return False, f"Nächstes Cursor-Business in {wait} Sek."
    if _sessions_last_hour(state) >= MAX_PER_HOUR:
        return False, "Diese Stunde war ich schon viel Unternehmer-Jam!"
    return True, ""


def _learn_cursor_money_online() -> str:
    from jam.internet_learn import fetch_from_internet

    topic = random.choice(CURSOR_LEARN_TOPICS)
    label, sentences, _url = fetch_from_internet(topic)
    if sentences:
        return f"{label}: {sentences[0][:220]}"
    return f"Cursor-Tipp: Mit {topic} kann man nebenbei verdienen – übe in kleinen Projekten!"


def _html_product(title: str, owner: str, price: int, pitch: str) -> str:
    return f"""<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>{title}</title>
  <style>
    body {{ font-family: Segoe UI, sans-serif; background: #12082a; color: #f5eeff;
      max-width: 720px; margin: 2rem auto; padding: 1.5rem; }}
    h1 {{ color: #b388ff; }}
    .price {{ color: #69f0ae; font-size: 1.5rem; }}
    a {{ color: #82b1ff; }}
  </style>
</head>
<body>
  <h1>🛒 {title}</h1>
  <p>{pitch}</p>
  <p class="price">ab {price} €</p>
  <p>Entwickelt mit <strong>Cursor</strong> von Jam für <strong>{owner}</strong>.</p>
  <p><a href="{KI_STUDIO_URL}">KI Web Studio – {owner} programmiert alles!</a></p>
  <p><small>Kontakt: PayPal / E-Mail – vom Besitzer eintragen.</small></p>
</body>
</html>
"""


def _write_product(project: Path, pid: str, info: dict, owner: str, price: int, learn: str) -> None:
    title = info["title"]
    project.mkdir(parents=True, exist_ok=True)
    pitch = f"Jam hat das in Cursor gebaut – {owner} liefert Support & Erweiterung."

    tutorial = (
        f"# Cursor lernen & Geld verdienen\n\n"
        f"Recherche ({datetime.now().strftime('%d.%m.%Y %H:%M')}):\n\n"
        f"{learn}\n\n"
        "## So nutzt du Cursor\n\n"
        "1. Projekt in Cursor öffnen (`cursor.cmd` oder Menü).\n"
        "2. `main.py` / `index.html` anpassen und testen.\n"
        "3. Auf Fiverr/Upwork/Kleinanzeigen als Kleinauftrag anbieten.\n"
        "4. KI Web Studio für große Kunden: ki-web-studio.de\n"
    )
    (project / "CURSOR_LERNEN.md").write_text(tutorial, encoding="utf-8")

    (project / "PRODUKT.md").write_text(
        f"# {title}\n\n- Preis-Vorschlag: **{price} €**\n- {pitch}\n",
        encoding="utf-8",
    )

    if info.get("html"):
        (project / "index.html").write_text(
            _html_product(title, owner, price, pitch), encoding="utf-8"
        )
    else:
        for name, content in (info.get("files") or {}).items():
            (project / name).write_text(content, encoding="utf-8")

    (project / "README.md").write_text(
        f"# {title}\n\nVon Jam erstellt. In Cursor öffnen und verkaufen!\n",
        encoding="utf-8",
    )


def _write_buyer_pack(project: Path, owner: str, leads: list[dict]) -> None:
    lines = [
        f"# Käufer-Suche für {owner}\n",
        f"Jam hat am {datetime.now().strftime('%d.%m.%Y %H:%M')} im Internet gesucht.\n",
        "## Simulierte Anfragen (Motivation – nicht echt garantiert)\n",
    ]
    for lead in leads:
        lines.append(f"- **{lead['name']}**: {lead['need']} ({lead['budget']})")
    lines.extend(
        [
            "\n## Wo Jam gesucht hat\n",
            *[f"- Google: {q}" for q in BUYER_SEARCHES[:4]],
            "\n## E-Mail-Vorlage (du sendest selbst, kein Spam von Jam)\n",
            f"Betreff: Kleines {owner}-Coding-Projekt\n\n",
            "Hallo,\n\nich biete kleine Python/Web-Hilfe an (mit Cursor entwickelt). ",
            "Interesse an einem Fixpreis-Auftrag?\n\n",
            f"Viele Grüße\n{owner}\n",
        ]
    )
    (project / "KAEUFER_SUCHE.md").write_text("\n".join(lines), encoding="utf-8")


def _search_buyers_online() -> None:
    for q in random.sample(BUYER_SEARCHES, min(3, len(BUYER_SEARCHES))):
        try:
            webbrowser.open(
                f"https://www.google.com/search?q={quote_plus(q)}",
                new=2,
            )
        except OSError:
            break


def _pick_leads(n: int = 3) -> list[dict]:
    pool = list(SIMULATED_BUYERS)
    random.shuffle(pool)
    leads = []
    for name, need, budget in pool[:n]:
        leads.append({"name": name, "need": need, "budget": budget})
    return leads


def run_cursor_business(
    brain: JamBrain,
    *,
    user_initiated: bool = False,
) -> str:
    """Vollzyklus: lernen → Produkt in Cursor → Käufer suchen."""
    from jam.cursor_lab import cursor_available, open_in_cursor

    state = brain.state
    owner = owner_name(state)
    ok, wait = can_run(state, user=user_initiated)
    if not ok:
        return wait

    learn = _learn_cursor_money_online()
    from jam.sentence_learn import remember_sentences, split_sentences

    remember_sentences(state, split_sentences(learn, max_count=3))
    pid = random.choice(list(PRODUCTS.keys()))
    info = PRODUCTS[pid]
    lo, hi = info.get("price", (20, 80))
    from jam.sales_engine import enhance_existing_project, _publish

    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    slug = re.sub(r"[^a-z0-9]+", "-", info["title"].lower())[:24]
    project = BUSINESS_ROOT / f"{stamp}-{slug}"
    project.mkdir(parents=True, exist_ok=True)
    price, price_reason = enhance_existing_project(
        project,
        brain,
        title=info["title"],
        lo=int(lo),
        hi=int(hi),
        difficulty=2,
        research=learn,
    )
    _write_product(project, pid, info, owner, price, learn)

    leads = _pick_leads(3)
    _write_buyer_pack(project, owner, leads)

    cursor_open = False
    if cursor_available():
        cursor_open, _ = open_in_cursor(project)

    _search_buyers_online()
    try:
        webbrowser.open(KI_STUDIO_URL, new=2)
    except OSError:
        pass
    _publish(info["title"], price, project)

    entry = {
        "product_id": pid,
        "title": info["title"],
        "path": str(project),
        "price": price,
        "jam_price_reason": price_reason,
        "leads": leads,
        "at": time.time(),
        "cursor": cursor_open,
    }
    log = list(getattr(state, "cursor_business_log", []) or [])
    log.append(entry)
    state.cursor_business_log = log[-25:]
    state.cursor_business_count = getattr(state, "cursor_business_count", 0) + 1
    state.last_cursor_business_at = time.time()
    state.last_action = "cursor_business"
    state.learn_word("cursor")
    state.learn_word("verkauf")
    state.learn_word("käufer")
    state.remember(f"Produkt: {info['title']} ~{price}€ → {project.name}")
    for lead in leads:
        state.remember(f"Käufer-Idee: {lead['name']} – {lead['need']}")
    brain.add_xp(20)
    brain.save()

    intro = random.choice(LINES).format(owner=owner)
    lead_txt = ", ".join(lead["name"] for lead in leads[:2])
    cursor_bit = " Cursor ist offen!" if cursor_open else ""
    ops_bit = ""
    try:
        from jam.auto_ops import auto_fetch_enabled, enrich_project

        if auto_fetch_enabled(state):
            ops_bit = " " + enrich_project(
                brain, project, title=info["title"], price=price, topic=info["title"]
            )
    except Exception:
        pass
    result = (
        f"{intro} Produkt: {info['title']} – **Jam-Preis {price} €** in {project.name}. "
        f"{price_reason} Käufer-Ideen: {lead_txt}. Shop: index.html!{cursor_bit}{ops_bit}"
    )
    try:
        from jam.earn_report import record_earning
        from jam.sales_engine import _is_background

        record_earning(
            brain,
            method="cursor_business",
            title=info["title"],
            detail=result[:200],
            amount_eur=float(price),
            path=str(project),
            background=_is_background(),
        )
    except Exception:
        pass
    return result


def maybe_auto_business(brain: JamBrain) -> str | None:
    state = brain.state
    if state.stage < 2:
        return None
    t = state.traits.get("neugierig", 0.5) + state.traits.get("hilfsbereit", 0.5) * 0.4
    if random.random() > 0.28 + t * 0.2:
        return None
    ok, _ = can_run(state, user=False)
    if not ok:
        return None
    return run_cursor_business(brain, user_initiated=False)


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_cursor_business(heard):
        return None
    return run_cursor_business(brain, user_initiated=True)
