"""
TikTok-Wachstums-Sprint: 1000 Follower in 7 Tagen (@socialmedia.mentor).

Jam liefert Plan, Content, Posting – echte Follower kommen von TikTok-Algorithmus + deinem Einsatz.
"""

from __future__ import annotations

import time
from datetime import datetime, timedelta
from pathlib import Path

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

GOAL_FOLLOWERS = 1000
GOAL_DAYS = 7
DEFAULT_START_FOLLOWERS = 16

GROWTH_ROOT = Path.home() / "Documents" / "Jam-TikTok-Posten"

DAILY_TASKS = (
    "3–4 Videos posten (Jam-Captions nutzen)",
    "Erste 30 Min.: 10–15 Kommentare bei Creator in deiner Nische",
    "Auf jeden Kommentar unter deinen Videos antworten",
    "1 Story / kurzes LIVE oder „Gerade gepostet“-Hinweis",
    "Bio + Link prüfen (klarer Nutzen: Mentor, Schnitt, Tipps)",
    "Hashtags: #socialmediamentor #tiktoktipps #reichweite #fyp",
    "1× täglich: Stock-Clip remixen (Jam: „TikTok Remix“) → hochladen",
)

BOOST_HOOKS = (
    "Tag {day}/7 – Ziel 1000 Follower. Heute: {tip}",
    "Wer mir folgt, bekommt morgen Tipp #{day} – Follow + Speichern",
    "Social Media Mentor – ich zeige dir was wirklich Views bringt",
)


def hears_follower_goal(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if not any(w in h for w in ("follower", "folger", "1000", "tausend")):
        return False
    if any(w in h for w in ("7", "sieben", "woche", "tagen", "tage")):
        return True
    if "bekommst" in h or "schaffst" in h or "hin" in h:
        if "follower" in h or "1000" in h:
            return True
    return False


def _deadline_ts(start: float) -> float:
    return start + GOAL_DAYS * 86400


def days_left(state: JamState) -> int:
    end = float(getattr(state, "jam_tiktok_goal_deadline", 0) or 0)
    if end <= 0:
        return GOAL_DAYS
    return max(0, int((end - time.time()) / 86400) + 1)


def followers_needed(state: JamState) -> int:
    goal = int(getattr(state, "jam_tiktok_follower_goal", GOAL_FOLLOWERS) or GOAL_FOLLOWERS)
    current = int(getattr(state, "jam_tiktok_followers_current", 0) or 0)
    start = int(getattr(state, "jam_tiktok_followers_start", DEFAULT_START_FOLLOWERS) or 0)
    base = current if current > 0 else start
    return max(0, goal - base)


def per_day_target(state: JamState) -> int:
    left = max(1, days_left(state))
    return int(round(followers_needed(state) / left))


def write_growth_plan_file(state: JamState) -> Path:
    GROWTH_ROOT.mkdir(parents=True, exist_ok=True)
    path = GROWTH_ROOT / "7-TAGE-1000-FOLLOWER-PLAN.md"
    start = int(getattr(state, "jam_tiktok_followers_start", DEFAULT_START_FOLLOWERS))
    goal = int(getattr(state, "jam_tiktok_follower_goal", GOAL_FOLLOWERS))
    need = followers_needed(state)
    daily = per_day_target(state)
    end = datetime.fromtimestamp(
        float(getattr(state, "jam_tiktok_goal_deadline", time.time() + 7 * 86400))
    )

    lines = [
        f"# 7-Tage-Sprint: {goal} Follower – @socialmedia.mentor",
        "",
        f"**Start:** ~{start} Follower · **Ziel:** {goal} · **Noch nötig:** ~{need}",
        f"**~{daily} neue Follower pro Tag** (Durchschnitt) · **Deadline:** {end.strftime('%d.%m.%Y')}",
        "",
        "## Jam macht automatisch",
        "- 3× Post (8:00 · 12:30 · 19:00) + optional 21:00 Boost",
        "- Captions & Hooks im Mentor-Stil (wie deine Top-Videos)",
        "- Upload öffnen + Text in Zwischenablage",
        "",
        "## David – täglich (entscheidend)",
    ]
    for t in DAILY_TASKS:
        lines.append(f"- {t}")
    lines.extend(
        [
            "",
            "## Realität",
            "1000 in 7 Tagen ist **ambitioniert** (~140/Tag). Mit starken Hooks, "
            "Konstanz und Kommentieren erhöht ihr die Chance. Ein viraler Clip kann das Ziel "
            "an einem Tag erfüllen.",
            "",
            "## Fortschritt eintragen",
            "Sag Jam: „TikTok Follower 250“ – dann rechne ich neu.",
            "",
            f"Stand: {datetime.now().strftime('%d.%m.%Y %H:%M')}",
        ]
    )
    path.write_text("\n".join(lines), encoding="utf-8")
    return path


def enable_growth_sprint(
    brain: JamBrain,
    *,
    start_followers: int = DEFAULT_START_FOLLOWERS,
    current_followers: int | None = None,
) -> str:
    from jam.tiktok_studio import grant_full_access, mark_browser_logged_in

    state = brain.state
    now = time.time()
    cur = current_followers if current_followers is not None else start_followers

    state.jam_tiktok_growth_sprint = True
    state.jam_tiktok_follower_goal = GOAL_FOLLOWERS
    state.jam_tiktok_followers_start = start_followers
    state.jam_tiktok_followers_current = cur
    state.jam_tiktok_goal_started_at = now
    state.jam_tiktok_goal_deadline = _deadline_ts(now)
    state.jam_tiktok_post_schedule = True
    state.jam_tiktok_full_access = True
    state.jam_all_tasks_stopped = False
    state.remember(f"TikTok Sprint: {GOAL_FOLLOWERS} Follower in {GOAL_DAYS} Tagen")
    state.last_action = "tiktok_growth_sprint"
    brain.add_xp(25)
    brain.save()

    cfg_path = Path(__file__).resolve().parent.parent / "data" / "tiktok-config.json"
    try:
        import json

        if cfg_path.is_file():
            cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
        else:
            cfg = {}
        cfg["growth_sprint"] = True
        cfg["follower_goal"] = GOAL_FOLLOWERS
        cfg["goal_days"] = GOAL_DAYS
        cfg["followers_start"] = start_followers
        cfg["followers_current"] = cur
        cfg["goal_deadline"] = state.jam_tiktok_goal_deadline
        cfg_path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
    except Exception:
        pass

    if not getattr(state, "jam_tiktok_browser_logged_in", False):
        mark_browser_logged_in(brain)
    else:
        grant_full_access(brain, granted_by=owner_name(state))

    plan = write_growth_plan_file(state)
    need = followers_needed(state)
    daily = per_day_target(state)
    left = days_left(state)
    owner = owner_name(state)

    return (
        f"**Ja {owner}, ich gebe alles!** @{state.tiktok_account or 'socialmedia.mentor'} – "
        f"Ziel **{GOAL_FOLLOWERS} Follower in {GOAL_DAYS} Tagen** (noch **~{need}**, "
        f"ca. **{daily}/Tag**). Ich poste **3–4× täglich**, Mentor-Hooks wie auf deinem Kanal. "
        f"Du: Videos + Kommentieren + antworten – das ist der Turbo. "
        f"Plan: **{plan.name}**. Noch **{left} Tage**. Ehrlich: hart, aber machbar mit einem Hit. "
        f"Fortschritt: „Jam, TikTok Follower 123“."
    )[:720]


def update_follower_count(brain: JamBrain, count: int) -> str:
    state = brain.state
    state.jam_tiktok_followers_current = count
    brain.save()
    write_growth_plan_file(state)
    need = followers_needed(state)
    daily = per_day_target(state)
    goal = int(getattr(state, "jam_tiktok_follower_goal", GOAL_FOLLOWERS))
    if count >= goal:
        return (
            f"🎉 **GESCHAFFT!** {count} Follower – Ziel {goal} erreicht! "
            f"@{getattr(state, 'tiktok_account', 'socialmedia.mentor')}"
        )[:400]
    return (
        f"Stand **{count}** Follower – noch **{need}** bis {goal} "
        f"(~{daily}/Tag in {days_left(state)} Tagen)."
    )[:400]


def parse_follower_count(text: str) -> int | None:
    import re

    h = text.lower()
    m = re.search(r"(\d{1,5})\s*(?:follower|folger)", h)
    if m:
        return int(m.group(1))
    if "tausend" in h or "1000" in h:
        return 1000
    return None


def growth_status_line(state: JamState) -> str:
    if not getattr(state, "jam_tiktok_growth_sprint", False):
        return ""
    cur = int(getattr(state, "jam_tiktok_followers_current", 0) or 0)
    start = int(getattr(state, "jam_tiktok_followers_start", 0) or 0)
    show = cur or start
    return (
        f"Sprint: {show}/{GOAL_FOLLOWERS} Follower · "
        f"noch {followers_needed(state)} · {days_left(state)} Tage"
    )


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    import re

    h = heard.lower()
    m = re.search(r"(?:follower|folger)\s*(?:sind|:)?\s*(\d+)", h)
    if m and "tiktok" in h:
        return update_follower_count(brain, int(m.group(1)))
    cnt = parse_follower_count(heard)
    if cnt and cnt < 5000 and "tiktok" in h and "ziel" not in h:
        return update_follower_count(brain, cnt)

    if hears_follower_goal(heard):
        start = DEFAULT_START_FOLLOWERS
        if "16" in heard:
            start = 16
        return enable_growth_sprint(brain, start_followers=start)
    return None


def is_sprint_active(state: JamState | None = None) -> bool:
    if state is not None:
        return bool(getattr(state, "jam_tiktok_growth_sprint", False))
    try:
        import json
        from pathlib import Path

        p = Path(__file__).resolve().parent.parent / "data" / "tiktok-config.json"
        if p.is_file():
            return bool(json.loads(p.read_text(encoding="utf-8")).get("growth_sprint"))
    except Exception:
        pass
    return False


def is_boost_slot_active(state: JamState | None = None) -> bool:
    """21:00 Extra-Post während Sprint."""
    if not is_sprint_active(state):
        return False
    now = datetime.now()
    return 20 <= now.hour < 22
