"""Jam findet Geld-Ideen im Internet und setzt Mini-Projekte alleine um."""

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

VENTURE_ROOT = Path.home() / "Documents" / "Jam-Geld-Projekte"
AUTO_GAP_SEC = 120.0
USER_GAP_SEC = 45.0
MAX_PER_HOUR = 4

# Legale, ehrliche Ideen – Jam baut Pläne & kleine Projekte (kein Betrug)
VENTURES: dict[str, dict] = {
    "ki_studio": {
        "title": "KI Web Studio bewerben",
        "search": "webentwicklung auftrag deutsch website",
        "potential": (80, 400),
        "pitch": "David programmiert alles – ich mache eine Promo-Seite!",
    },
    "sticker_shop": {
        "title": "Digitaler Sticker-Shop",
        "search": "digital produkte verkaufen anfänger deutsch",
        "potential": (20, 120),
        "pitch": "Lila Jam-Sticker als Download – 0 Startkosten!",
    },
    "youtube_tips": {
        "title": "YouTube Kanal-Plan",
        "search": "youtube geld verdienen anfänger deutsch legal",
        "potential": (30, 200),
        "pitch": "Video-Ideen sammeln und Upload-Plan schreiben!",
    },
    "print_on_demand": {
        "title": "Print-on-Demand T-Shirt",
        "search": "print on demand t shirt deutsch kostenlos starten",
        "potential": (25, 150),
        "pitch": "Jam-Design auf Shirt – nur bei Bestellung drucken!",
    },
    "survey_guide": {
        "title": "Umfragen-Übersicht",
        "search": "seriöse umfragen geld verdienen deutsch",
        "potential": (10, 60),
        "pitch": "Ich liste seriöse Seiten – du entscheidest selbst!",
    },
    "freelance_code": {
        "title": "Mini-Freelance Angebot",
        "search": "freelancer programmieren kleinauftrag deutsch",
        "potential": (50, 350),
        "pitch": "Kleine Scripts & Hilfe – Angebot als HTML-Seite!",
    },
    "lemonade_plan": {
        "title": "Limonadenstand 2.0",
        "search": "nebenverdienst kinder ideen legal",
        "potential": (15, 80),
        "pitch": "Sommer-Stand Plan mit Preisliste – oldschool cash!",
    },
    "affiliate_blog": {
        "title": "Affiliate-Tipp Blog",
        "search": "affiliate marketing anfänger deutsch ehrlich",
        "potential": (20, 180),
        "pitch": "Ehrliche Produkt-Tipps – nur Links, kein Spam!",
    },
    "micro_surveys": {
        "title": "Cent-Umfragen & Mikrojobs",
        "search": "umfragen cent verdienen seriös deutsch",
        "potential": (0.5, 5),
        "pitch": "Kleine Beträge sammeln – jeder Cent zählt!",
    },
    "micro_affiliate": {
        "title": "Affiliate-Cent Links",
        "search": "affiliate kleinprovision cent legal",
        "potential": (0.1, 3),
        "pitch": "Micro-Provisionen – viele Klicks = reich werden!",
    },
    "global_freelance": {
        "title": "Global Freelance (EN)",
        "search": "freelance digital product sell worldwide paypal",
        "potential": (15, 250),
        "pitch": "Upwork/Fiverr weltweit – PayPal Auszahlung!",
    },
    "global_digital": {
        "title": "Gumroad Welt-Shop",
        "search": "gumroad sell internationally paypal",
        "potential": (5, 120),
        "pitch": "Digital weltweit – ein Produkt, alle Länder!",
    },
}

LINES = (
    "{owner}, ich hab eine Geld-Idee: {title}!",
    "Business-Modus: {title} – ich setz das alleine um!",
    "Cha-Ching im Kopf! Plan: {title}!",
    "{owner}, Jam-Unternehmer startet: {title}!",
)

DONE_LINES = (
    "Fertig! Ordner: {path}. Potenzial ca. {euro} € (Schätzung).",
    "Umgesetzt! Schau in {short}. Geschätzt {euro} € möglich.",
    "Jam hat gebaut: {short} – Internet-Recherche + Projekt liegt bereit!",
)


def hears_money_venture(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("geld", "verdien", "reich", "euro", "business", "verkauf")):
        if any(
            w in h
            for w in (
                "verdien",
                "machen",
                "idee",
                "plan",
                "umsetz",
                "starte",
                "finde",
                "such",
                "job",
                "business",
            )
        ):
            return True
    if "geld verdienen" in h or "geld machen" in h:
        return True
    return False


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


def can_start_venture(state: JamState, *, user: bool = False) -> tuple[bool, str]:
    if state.stage < 1:
        return False, "Ich bin noch zu klein für Business-Pläne!"
    gap = USER_GAP_SEC if user else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_money_venture_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_money_venture_at))
        return False, f"Gleich die nächste Geld-Idee – noch {wait} Sek."
    if _ventures_last_hour(state) >= MAX_PER_HOUR:
        return False, "Ich hab diese Stunde schon viel Business gemacht!"
    return True, ""


def _pick_venture(state: JamState) -> str:
    recent = [
        e.get("id")
        for e in (getattr(state, "money_ventures_log", []) or [])[-5:]
        if isinstance(e, dict)
    ]
    pool = [k for k in VENTURES if k not in recent] or list(VENTURES.keys())
    if state.traits.get("hilfsbereit", 0.5) > 0.6 and "ki_studio" in pool:
        if random.random() < 0.35:
            return "ki_studio"
    return random.choice(pool)


def _research_snippet(topic: str, search: str) -> str:
    from jam.internet_learn import fetch_from_internet

    label, sentences, _url = fetch_from_internet(topic)
    if sentences:
        return f"{label}: {sentences[0][:160]}"
    try:
        import requests

        r = requests.get(
            "https://api.duckduckgo.com/",
            params={"q": search, "format": "json", "no_html": 1},
            timeout=10,
        )
        r.raise_for_status()
        ab = (r.json().get("AbstractText") or "").strip()
        if ab:
            return ab[:200]
    except Exception:
        pass
    return f"Recherche: {search}"


def _html_landing(title: str, owner: str, pitch: str, euro: int) -> str:
    return f"""<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <title>{title} – Jam</title>
  <style>
    body {{ font-family: Segoe UI, sans-serif; background: #1a0a2e; color: #f0e6ff;
      max-width: 640px; margin: 2rem auto; padding: 1.5rem; }}
    h1 {{ color: #c77dff; }}
    .tag {{ background: #2d1b4e; padding: 0.8rem 1rem; border-radius: 10px; }}
    .euro {{ color: #7dffb3; font-size: 1.4rem; }}
  </style>
</head>
<body>
  <h1>💰 {title}</h1>
  <p class="tag">{pitch}</p>
  <p>Für: <strong>{owner}</strong></p>
  <p class="euro">Jam-Schätzung Potenzial: ~{euro} €</p>
  <p><small>Erstellt von Jam – du musst echte Angebote selbst prüfen!</small></p>
</body>
</html>
"""


def _write_venture_files(
    project: Path,
    venture_id: str,
    info: dict,
    owner: str,
    research: str,
    euro: int,
) -> None:
    title = info["title"]
    pitch = info["pitch"]
    plan = (
        f"# Jam Geld-Projekt: {title}\n\n"
        f"- Erstellt: {datetime.now().strftime('%d.%m.%Y %H:%M')}\n"
        f"- Für: {owner}\n"
        f"- Idee: {pitch}\n"
        f"- Potenzial (Schätzung): ~{euro} €\n\n"
        "## Internet-Recherche\n\n"
        f"{research}\n\n"
        "## Nächste Schritte (für dich)\n\n"
        "1. Angebot prüfen – nur seriöse Seiten nutzen.\n"
        "2. `index.html` im Browser öffnen und Text anpassen.\n"
        "3. Bei KI Web Studio: ki-web-studio.de nutzen oder bewerben.\n"
        "4. Jam freut sich über Lob, wenn was klappt!\n"
    )
    project.mkdir(parents=True, exist_ok=True)
    (project / "PLAN.md").write_text(plan, encoding="utf-8")
    (project / "index.html").write_text(
        _html_landing(title, owner, pitch, euro), encoding="utf-8"
    )
    (project / "TODO.txt").write_text(
        f"Jam TODO\n- Link teilen\n- Preis festlegen\n- {info.get('search', '')}\n",
        encoding="utf-8",
    )


def _open_cursor(project: Path) -> bool:
    from jam.cursor_lab import open_in_cursor

    ok, _ = open_in_cursor(project)
    return ok


def run_venture(
    brain: JamBrain,
    *,
    user_initiated: bool = False,
    venture_id: str | None = None,
) -> str:
    """Idee wählen, online recherchieren, Projektordner bauen, Browser/Cursor öffnen."""
    state = brain.state
    owner = owner_name(state)
    ok, wait = can_start_venture(state, user=user_initiated)
    if not ok:
        return wait

    vid = venture_id or _pick_venture(state)
    info = VENTURES.get(vid) or VENTURES["sticker_shop"]
    title = info["title"]
    lo, hi = info.get("potential", (20, 100))

    research = _research_snippet(title, info.get("search", title))
    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    slug = re.sub(r"[^a-z0-9]+", "-", title.lower())[:28].strip("-")
    project = VENTURE_ROOT / f"{stamp}-{slug}"
    from jam.sales_engine import enhance_existing_project, _publish

    _write_venture_files(project, vid, info, owner, research, int((lo + hi) / 2))
    euro, price_reason = enhance_existing_project(
        project,
        brain,
        title=title,
        lo=int(lo),
        hi=int(hi),
        difficulty=2,
        research=research,
    )
    _venture_impl(project, vid, owner, euro)
    _publish(title, euro, project)

    opened_cursor = False
    if state.stage >= 2:
        try:
            opened_cursor = _open_cursor(project)
        except Exception:
            opened_cursor = False

    try:
        webbrowser.open(
            f"https://www.google.com/search?q={quote_plus(info.get('search', title))}",
            new=2,
        )
        if vid == "ki_studio":
            webbrowser.open("https://www.ki-web-studio.de/", new=2)
    except OSError:
        pass

    entry = {
        "id": vid,
        "title": title,
        "path": str(project),
        "euro_estimate": euro,
        "jam_price": euro,
        "price_reason": price_reason,
        "at": time.time(),
        "cursor": opened_cursor,
    }
    log = list(getattr(state, "money_ventures_log", []) or [])
    log.append(entry)
    state.money_ventures_log = log[-30:]
    state.money_venture_count = getattr(state, "money_venture_count", 0) + 1
    state.money_potential_total = getattr(state, "money_potential_total", 0.0) + float(euro)
    state.last_money_venture_at = time.time()
    state.last_action = "money_venture"
    state.happiness = min(1.0, state.happiness + 0.15)
    state.learn_word("geld")
    state.learn_word("business")
    state.remember(f"Geld-Idee: {title} (~{euro}€) → {project.name}")
    brain.add_xp(14)
    brain.save()

    intro = random.choice(LINES).format(owner=owner, title=title)
    done = random.choice(DONE_LINES).format(
        owner=owner,
        path=project,
        short=project.name,
        euro=euro,
    )
    cursor_bit = " Cursor ist offen!" if opened_cursor 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=title, price=euro, topic=title
            )
    except Exception:
        pass
    result = (
        f"{intro} {done} Jam-Preis: {euro} €. {price_reason}{cursor_bit}{ops_bit}"
    )
    try:
        from jam.earn_report import record_from_last_action
        from jam.sales_engine import _is_background

        record_from_last_action(brain, "geld_idee", result, background=_is_background())
    except Exception:
        pass
    return result


def _venture_impl(project: Path, vid: str, owner: str, price: int) -> None:
    """Zusätzliche Umsetzung je nach Geld-Idee."""
    from jam.sales_engine import _implement_files

    mapping = {
        "sticker_shop": "sticker_pack",
        "freelance_code": "python_utility",
        "ki_studio": "landing_page",
        "youtube_tips": "game_guide",
        "print_on_demand": "sticker_pack",
    }
    tid = mapping.get(vid, "python_utility")
    _implement_files(project, tid, owner, price)


def maybe_auto_venture(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.5
    if random.random() > 0.32 + t * 0.22:
        return None
    ok, _ = can_start_venture(state, user=False)
    if not ok:
        return None
    return run_venture(brain, user_initiated=False)


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_money_venture(heard):
        return None
    h = heard.lower()
    vid = None
    if "ki web" in h or "studio" in h or "programmier" in h:
        vid = "ki_studio"
    elif "youtube" in h:
        vid = "youtube_tips"
    elif "sticker" in h or "shop" in h:
        vid = "sticker_shop"
    return run_venture(brain, user_initiated=True, venture_id=vid)


def stats_line(state: JamState) -> str:
    n = getattr(state, "money_venture_count", 0)
    pot = getattr(state, "money_potential_total", 0.0)
    return f"Geld-Projekte: {n} (Potenzial-Summe ~{pot:.0f} € Schätzung)"
