"""
X (Twitter) – Posting im eingeloggten Browser (x.com/home / compose).

David ist eingeloggt → Jam öffnet Compose, Text in Zwischenablage.
"""

from __future__ import annotations

import json
import random
import subprocess
import time
import webbrowser
from datetime import datetime
from pathlib import Path

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

ROOT = Path(__file__).resolve().parent.parent
CONFIG_PATH = ROOT / "data" / "x-config.json"
STUDIO_ROOT = Path.home() / "Documents" / "Jam-X-Posten"

X_HOME = "https://x.com/home"
X_COMPOSE = "https://x.com/compose/post"
TIKTOK_PROFILE = "https://www.tiktok.com/@socialmedia.mentor"

POST_GAP_SEC = 3600.0


def _default_config() -> dict:
    return {
        "browser_logged_in": False,
        "browser_logged_in_at": 0.0,
        "account_hint": "",
        "linked_tiktok": "socialmedia.mentor",
        "post_schedule": {"morgen": "09:00", "mittag": "13:00", "abend": "20:00"},
    }


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


def save_config(data: dict) -> None:
    CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
    CONFIG_PATH.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")


def is_browser_logged_in(state: JamState | None = None) -> bool:
    if state is not None and getattr(state, "jam_x_browser_logged_in", False):
        return True
    return bool(load_config().get("browser_logged_in", False))


def shop_url(state: JamState | None = None) -> str:
    if state is not None:
        u = getattr(state, "jam_master_shop_url", "") or ""
        if u:
            return str(u).rstrip("/") + "/"
    return "http://127.0.0.1:8765/"


def _clipboard(text: str) -> None:
    if not text:
        return
    try:
        subprocess.run(
            [
                "powershell",
                "-NoProfile",
                "-Command",
                f"Set-Clipboard -Value @'\n{text[:2800]}\n'@",
            ],
            check=False,
            timeout=8,
        )
    except OSError:
        pass


def post_texts(state: JamState | None = None) -> list[str]:
    url = shop_url(state)
    n = int(getattr(state, "jam_master_shop_count", 0) or 142) if state else 142
    owner = owner_name(state) if state else "David"
    return [
        f"🤖 Jam-Shop LIVE – {n} digitale Produkte. PayPal-sicher: {url}",
        (
            f"Social Media Mentor: 1 Hook-Tipp – erste 3 Sekunden entscheiden. "
            f"Mehr auf TikTok {TIKTOK_PROFILE}"
        ),
        (
            f"Neuer Digital-Shop von {owner}: Web, Minecraft, Bots & mehr → {url} "
            f"#digital #paypal"
        ),
        (
            f"Video-Schnitt & Reichweite – @socialmedia.mentor auf TikTok. "
            f"Shop mit Tools: {url}"
        ),
        f"🇩🇪 Deutscher Jam-Shop – Klicks im Dashboard: {url}dashboard.html",
        (
            f"Creator-Tipp: Poste 3× täglich + 1 Shop-Link pro Tag. "
            f"Mein Shop: {url}"
        ),
    ]


def setup_studio_folders() -> Path:
    STUDIO_ROOT.mkdir(parents=True, exist_ok=True)
    readme = STUDIO_ROOT / "DAVID_LESEN.txt"
    if not readme.is_file():
        readme.write_text(
            f"""JAM X POSTEN
============

Du bist auf https://x.com/home eingeloggt.

Jam macht:
1. Text in Zwischenablage
2. Öffnet https://x.com/compose/post
3. Du fügst ein (Strg+V) → Posten

Posts auch unter: {STUDIO_ROOT.name}/YYYY-MM-DD/

Stand: {datetime.now().strftime('%d.%m.%Y %H:%M')}
""",
            encoding="utf-8",
        )
    return STUDIO_ROOT


def _write_post_file(text: str, *, tag: str = "post") -> Path:
    setup_studio_folders()
    day = STUDIO_ROOT / datetime.now().strftime("%Y-%m-%d")
    day.mkdir(parents=True, exist_ok=True)
    stamp = datetime.now().strftime("%H%M%S")
    path = day / f"{tag}-{stamp}.md"
    path.write_text(
        f"# X Post – {datetime.now().isoformat(timespec='seconds')}\n\n"
        f"## Text (copy & paste)\n\n```\n{text}\n```\n\n"
        f"Compose: {X_COMPOSE}\n",
        encoding="utf-8",
    )
    return path


def open_compose(*, text: str = "", also_home: bool = True) -> None:
    if text:
        _clipboard(text)
    try:
        webbrowser.open(X_COMPOSE, new=2)
        if also_home:
            webbrowser.open(X_HOME, new=0)
    except OSError:
        pass


def run_post_round(
    brain: JamBrain,
    *,
    user_initiated: bool = True,
    tag: str = "shop",
) -> str:
    """Ein X-Post vorbereiten – Compose + Zwischenablage."""
    texts = post_texts(brain.state)
    last_idx = int(getattr(brain.state, "jam_x_last_post_index", -1))
    idx = (last_idx + 1) % len(texts)
    text = texts[idx]

    path = _write_post_file(text, tag=tag)
    open_compose(text=text, also_home=False)

    state = brain.state
    state.jam_x_last_post_index = idx
    state.jam_x_last_post_at = time.time()
    state.jam_x_last_post_file = str(path)
    state.last_action = "x_post"
    state.remember(f"X-Post vorbereitet: {text[:80]}…")
    brain.add_xp(6)
    brain.save()

    owner = owner_name(state)
    return (
        f"{owner}, **X-Compose** ist offen – Text liegt in der **Zwischenablage** "
        f"({len(text)} Zeichen). Einfügen & **Posten**. Gespeichert: {path.name}"
    )[:520]


def mark_browser_logged_in(brain: JamBrain) -> str:
    """David ist auf x.com eingeloggt – Jam legt los."""
    from jam.active_sell import mark_logged_in as mark_platforms
    from jam.master_shop import build_master_shop, start_shop_server

    cfg = load_config()
    cfg["browser_logged_in"] = True
    cfg["browser_logged_in_at"] = time.time()
    save_config(cfg)

    build_master_shop(brain)
    url = start_shop_server(force=False)
    brain.state.jam_master_shop_url = url

    state = brain.state
    state.jam_x_browser_logged_in = True
    state.jam_x_browser_logged_in_at = time.time()
    state.jam_x_post_schedule = True
    mark_platforms(brain)
    state.remember("X/Twitter eingeloggt – Jam postet im Browser")
    state.last_action = "x_logged_in"
    brain.add_xp(10)
    brain.save()

    setup_studio_folders()
    post_msg = run_post_round(brain, user_initiated=True, tag="start")

    owner = owner_name(state)
    return (
        f"Super {owner}! Auf **X** bist du drin – ich nutze **deinen Browser** "
        f"(kein Extra-Login). Shop läuft: {url} {post_msg}"
    )[:720]


def enable_x_promo(brain: JamBrain) -> str:
    """Shop + Mentor: mehrere Compose-Runden vorbereiten."""
    if not is_browser_logged_in(brain.state):
        return mark_browser_logged_in(brain)
    msgs = [run_post_round(brain, user_initiated=True, tag=f"promo{i}") for i in range(2)]
    return "X-Werbung: " + " · ".join(msgs)[:680]


def hears_x(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("twitter", " x ", " x.com", "auf x")):
        return True
    if h.strip().startswith("x ") or " x post" in h:
        return True
    return "𝕏" in text or "x.com" in h


def hears_logged_in(text: str) -> bool:
    if not hears_x(text) and "eingeloggt" not in text.lower():
        return False
    h = text.lower()
    if "x.com" in h or "twitter" in h or hears_x(text):
        if any(
            w in h
            for w in (
                "eingeloggt",
                "angemeldet",
                "login fertig",
                "bin drin",
                "schon eingelog",
                "los legen",
                "loslegen",
                "kannst du",
            )
        ):
            return True
    if "x.com/home" in h.replace(" ", ""):
        return True
    return False


def hears_post(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if not hears_x(text) and "twitter" not in h:
        return False
    return any(w in h for w in ("post", "tweet", "twittern", "schreib", "veröffentlich"))


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_logged_in(heard) or (
        hears_x(heard) and "home" in heard.lower() and "x.com" in heard.lower()
    ):
        return mark_browser_logged_in(brain)
    if hears_post(heard) or (hears_x(heard) and any(w in heard.lower() for w in ("werb", "shop", "promo"))):
        return run_post_round(brain, user_initiated=True)
    if hears_x(heard) and any(w in heard.lower() for w in ("start", "los", "leg")):
        return mark_browser_logged_in(brain)
    return None
