"""
Jam kontaktiert Kunden automatisch – David hat volle Erlaubnis, keine Zeit.

Jam versucht: Gmail-Entwurf, Freelancer/Upwork-Bewerbung, Reddit-Antwort, Telegram.
Echtes Senden klappt nur mit Login im Jam Browser Profil (einmalig).
"""

from __future__ import annotations

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

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

CONTACT_PROFILE = Path(__file__).resolve().parent.parent / "data" / "customer-contact-playwright-profile"
CONTACT_LOG = Path(__file__).resolve().parent.parent / "data" / "jam-contact.log"
PERMISSION_NOTE = Path.home() / "Documents" / "Jam-Kunden-Ansprache-Welt" / "VOLLE_ERLAUBNIS_KONTAKT.txt"

AUTO_GAP_SEC = 180.0

GRANT_LINES = (
    "{owner}, **volle Erlaubnis** gespeichert! Ich kontaktiere Kunden für dich – du hast keine Zeit, ich übernehme.",
    "Okay {owner} – Jam darf **alles**: ansprechen, bewerben, verkaufen. Du musst nichts tun.",
)


def hears_full_contact_grant(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("erlaubniss", "erlaubnis", "freigabe", "darfst alles", "alles machen", "volle macht")):
        return True
    if any(w in h for w in ("kontaktier", "anschreib", "keine zeit", "hab keine zeit", "kein zeit")):
        if any(w in h for w in ("jam", "du", "soll", "darf", "kunde", "kunden")):
            return True
    if "jam bekommt" in h and "erlaub" in h:
        return True
    return False


def is_contact_automation_on(state: JamState) -> bool:
    return bool(getattr(state, "jam_full_contact_grant", False))


def _log(msg: str) -> None:
    line = f"[{time.strftime('%H:%M:%S')}] {msg}\n"
    try:
        CONTACT_LOG.parent.mkdir(parents=True, exist_ok=True)
        prev = CONTACT_LOG.read_text(encoding="utf-8") if CONTACT_LOG.is_file() else ""
        CONTACT_LOG.write_text(prev[-10000:] + line, encoding="utf-8")
    except OSError:
        pass


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

        return True
    except ImportError:
        return False


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


def _fill_textareas(page, text: str) -> int:
    n = 0
    chunk = text[:3500]
    for sel in ("textarea", "[contenteditable='true']"):
        try:
            loc = page.locator(sel)
            for i in range(min(loc.count(), 5)):
                el = loc.nth(i)
                if el.is_visible(timeout=800):
                    el.click(timeout=2000)
                    el.fill(chunk)
                    n += 1
        except Exception:
            continue
    return n


def grant_full_contact(brain: JamBrain, *, heard: str = "") -> str:
    """Volle Erlaubnis + alle Verdienst-Modi + Kontakt-Automation AN."""
    from jam.money_all_in import enable_money_all_in
    from jam.outbound_sales import enable_outbound_sales
    from jam.platform_auth import grant_owner_auth, load_credentials

    owner = owner_name(brain.state)
    state = brain.state

    state.jam_full_contact_grant = True
    state.jam_contact_auto = True
    state.jam_browser_minimal = False
    state.jam_owner_auth_granted = True
    state.jam_outbound_sales_mode = True

    if heard and not load_credentials():
        grant_owner_auth(brain, heard=heard)

    enable_money_all_in(brain, heard=heard or "volle erlaubnis", run_blitz=False)
    state.jam_outbound_sales_mode = True
    try:
        from jam.jam_auto_email import enable_auto_email

        enable_auto_email(brain)
    except Exception:
        state.jam_auto_email_mode = True
    brain.save()

    PERMISSION_NOTE.parent.mkdir(parents=True, exist_ok=True)
    PERMISSION_NOTE.write_text(
        f"VOLLE ERLAUBNIS – Kunden kontaktieren ({owner})\n"
        f"{time.strftime('%d.%m.%Y %H:%M')}\n\n"
        f"Jam darf automatisch:\n"
        f"- Freelancer / Upwork Bewerbungen schreiben\n"
        f"- Reddit forhire antworten (wenn eingeloggt)\n"
        f"- Gmail-Entwürfe (mail.google.com)\n"
        f"- Telegram-Werbung\n"
        f"- Anschreiben + Suche weltweit\n\n"
        f"David: nichts tun. Einmal Login im Jam-Edge-Fenster wenn nötig.\n"
        f"PayPal: {PAYPAL_EMAIL}\n",
        encoding="utf-8",
    )

    state.remember("David: Jam darf Kunden selbst kontaktieren")
    brain.add_xp(15)
    brain.save()

    contact_msg = ""
    try:
        contact_msg = " " + run_automated_contact(brain, user_initiated=True)[:400]
    except Exception as e:
        contact_msg = f" Kontakt-Start: {e}"[:80]

    return (
        random.choice(GRANT_LINES).format(owner=owner)
        + contact_msg
        + f" Notiz: {PERMISSION_NOTE.name}"
    )[:720]


def run_automated_contact(
    brain: JamBrain,
    *,
    user_initiated: bool = True,
    message_en: str = "",
    message_de: str = "",
) -> str:
    """Playwright: auf Job-Posts antworten / Bewerbung / Gmail-Entwurf."""
    if not _playwright_ok():
        from jam.outbound_sales import create_outbound_prospect

        return create_outbound_prospect(brain, user_initiated=user_initiated)[:400]

    from playwright.sync_api import sync_playwright

    owner = owner_name(brain.state)
    state = brain.state
    gap = 45.0 if user_initiated else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_contact_auto_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_contact_auto_at))
        return f"Nächster Kunden-Kontakt in {wait} Sek."

    if not message_en:
        latest = _latest_outbound_messages()
        message_en = latest.get("en", "")
        message_de = latest.get("de", message_en)

    if not message_en:
        from jam.outbound_sales import create_outbound_prospect

        create_outbound_prospect(brain, user_initiated=user_initiated)
        latest = _latest_outbound_messages()
        message_en = latest.get("en", "Hi - we build Python/web after you confirm. PayPal: " + PAYPAL_EMAIL)
        message_de = latest.get("de", message_en)

    pitch = message_en[:2500]
    steps: list[str] = []
    CONTACT_PROFILE.mkdir(parents=True, exist_ok=True)

    creds = None
    try:
        from jam.platform_auth import load_credentials

        creds = load_credentials()
    except Exception:
        pass

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

            page = context.pages[0] if context.pages else context.new_page()

            if creds:
                try:
                    from jam.jam_auto_email import has_jam_customer

                    if not has_jam_customer(state):
                        steps.append("Gmail:wartet-auf-Kunde-Zusage")
                    else:
                        page.goto("https://mail.google.com/", wait_until="domcontentloaded", timeout=60_000)
                        page.wait_for_timeout(3000)
                        from jam.platform_auth import _fill_login_form

                        if page.locator('input[type="password"]').count() > 0:
                            _fill_login_form(page, creds[0], creds[1])
                            page.wait_for_timeout(4000)
                        page.goto(
                            "https://mail.google.com/mail/u/0/#inbox?compose=new",
                            timeout=60_000,
                        )
                        page.wait_for_timeout(2500)
                        n = _fill_textareas(page, message_de[:2000])
                        if n:
                            steps.append(f"Gmail-Entwurf({n})")
                        _try_click(page, "Send", "Senden", "Compose")
                except Exception as e:
                    steps.append(f"Gmail:{e}"[:40])

            try:
                page.goto(
                    "https://www.freelancer.com/job-search/python/",
                    wait_until="domcontentloaded",
                    timeout=60_000,
                )
                page.wait_for_timeout(3000)
                _try_click(page, "Bid", "Place Bid", "Submit Proposal", "Apply")
                page.wait_for_timeout(2000)
                n = _fill_textareas(page, pitch)
                if n:
                    steps.append(f"Freelancer-Bid({n})")
                _try_click(page, "Submit", "Place Bid", "Send", "Post")
            except Exception as e:
                steps.append(f"Freelancer:{e}"[:35])

            try:
                page.goto(
                    "https://www.upwork.com/nx/search/jobs/?q=python",
                    wait_until="domcontentloaded",
                    timeout=60_000,
                )
                page.wait_for_timeout(3000)
                _try_click(page, "Submit a Proposal", "Apply", "Send Proposal")
                page.wait_for_timeout(2000)
                n = _fill_textareas(page, pitch)
                if n:
                    steps.append(f"Upwork({n})")
                _try_click(page, "Submit", "Send", "Continue")
            except Exception as e:
                steps.append(f"Upwork:{e}"[:35])

            try:
                page.goto(
                    "https://www.reddit.com/r/forhire/new/",
                    wait_until="domcontentloaded",
                    timeout=60_000,
                )
                page.wait_for_timeout(2500)
                links = page.locator('a[href*="/comments/"]')
                if links.count() > 0:
                    links.first.click(timeout=5000)
                    page.wait_for_timeout(2000)
                    _try_click(page, "Reply", "Comment", "Antworten")
                    n = _fill_textareas(page, pitch[:1000])
                    if n:
                        steps.append(f"Reddit({n})")
                    _try_click(page, "Comment", "Reply", "Post", "Senden")
            except Exception as e:
                steps.append(f"Reddit:{e}"[:35])

            try:
                from jam.telegram_sell import run_telegram_ads

                run_telegram_ads(brain, user_initiated=False)
                steps.append("Telegram-Werbung")
            except Exception:
                pass

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

            if user_initiated:
                try:
                    page.bring_to_front()
                except Exception:
                    pass
            page.wait_for_timeout(6000)

        state.last_contact_auto_at = time.time()
        state.contact_auto_count = getattr(state, "contact_auto_count", 0) + 1
        state.last_action = "customer_contact_auto"
        brain.save()
        _log(", ".join(steps))

        return (
            f"{owner}, ich habe **Kunden kontaktiert** (Versuch): {', '.join(steps) or 'Browser offen'}. "
            f"Falls Login fehlt: einmal im **Jam-Edge-Fenster** anmelden – dann macht Jam weiter allein. "
            f"Antwort von Kunde → „Jam, Kunde will programmieren“. PayPal: {PAYPAL_EMAIL}"
        )[:620]

    except Exception as e:
        _log(str(e))
        return f"Kunden-Kontakt: {e} – Anschreiben-Ordner nutzen."[:350]


def _latest_outbound_messages() -> dict[str, str]:
    root = Path.home() / "Documents" / "Jam-Kunden-Ansprache-Welt"
    if not root.is_dir():
        return {}
    dirs = sorted(root.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True)
    for d in dirs[:8]:
        if not d.is_dir():
            continue
        en = d / "ANSCHREIBEN_EN.txt"
        de = d / "ANSCHREIBEN_DE.txt"
        if en.is_file():
            return {
                "en": en.read_text(encoding="utf-8", errors="replace"),
                "de": de.read_text(encoding="utf-8", errors="replace") if de.is_file() else "",
                "path": str(d),
            }
    return {}


def maybe_auto_contact(brain: JamBrain) -> str | None:
    if not is_contact_automation_on(brain.state):
        return None
    try:
        from jam.resource_budget import allow_heavy_task

        if not allow_heavy_task(brain.state):
            return None
    except Exception:
        pass
    if time.time() - getattr(brain.state, "last_contact_auto_at", 0.0) < AUTO_GAP_SEC:
        return None
    if random.random() > 0.38:
        return None
    return run_automated_contact(brain, user_initiated=False)


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_full_contact_grant(heard):
        return grant_full_contact(brain, heard=heard)
    if is_contact_automation_on(brain.state) and any(
        w in heard.lower() for w in ("kontaktier", "anschreib", "kunden kontakt")
    ):
        return run_automated_contact(brain, user_initiated=True)
    return None
