#!/usr/bin/env python3
"""Weekly TikTok trend research agent: TokConnect REST API + Claude tool use.

Setup:   pip install requests anthropic
Env:     TOKCONNECT_API_KEY  (https://app.tokconnect.com/api-key)
         ANTHROPIC_API_KEY
Run:     python trend_agent.py pull  --niche "skincare"      # data only, no Claude
         python trend_agent.py agent --niche "skincare"      # full weekly brief
Optional: SLACK_WEBHOOK_URL, or SMTP_HOST/SMTP_USER/SMTP_PASSWORD/MAIL_TO/MAIL_FROM
"""
# --- part 1: TokConnect client and tools ---
import argparse
import datetime
import json
import os
import smtplib
import sys
import time
from email.message import EmailMessage

import requests

API = "https://api.tokconnect.com"


class TokConnectFatal(Exception):
    """Bad key or no credits: nothing the agent can fix, so stop the run."""


class TokConnectError(Exception):
    """A call failed in a way the model can react to (bad argument, upstream error)."""


class TokConnect:
    def __init__(self, api_key, max_calls=20):
        self.http = requests.Session()
        self.http.headers.update({"X-API-Key": api_key, "Accept": "application/json"})
        self.max_calls = max_calls
        self.calls = 0       # successful calls this run
        self.credits = 0     # credits charged this run
        self.remaining = None

    def get(self, path, **params):
        if self.calls >= self.max_calls:
            raise TokConnectError(f"Call budget of {self.max_calls} reached. Write the brief with what you have.")
        params = {k: v for k, v in params.items() if v is not None}
        for attempt in range(4):
            try:
                r = self.http.get(API + path, params=params, timeout=60)
            except requests.RequestException as exc:
                if attempt == 3:
                    raise TokConnectError(f"Network error: {exc}") from exc
                time.sleep(2 ** attempt)
                continue
            if r.status_code == 200:
                body = r.json()
                meta = body.get("meta", {})
                self.calls += 1
                self.credits += meta.get("credits_charged", 1)
                self.remaining = meta.get("credits_remaining", self.remaining)
                return body["data"]
            err = (r.json().get("error", {}) if r.headers.get("content-type", "").startswith("application/json") else {})
            if r.status_code == 401:
                raise TokConnectFatal("401: missing or revoked TokConnect key. Check TOKCONNECT_API_KEY.")
            if r.status_code == 402:
                raise TokConnectFatal("402: out of credits for this period. Upgrade or wait for renewal.")
            if r.status_code == 429 or r.status_code >= 500:
                wait = int(r.headers.get("Retry-After", 2 ** attempt * 2))
                if attempt == 3:
                    raise TokConnectError(f"{r.status_code} after retries: {err.get('message', '')}")
                time.sleep(min(wait, 60))   # failed calls are not charged, so retrying is free
                continue
            raise TokConnectError(f"{r.status_code} {err.get('type', '')}: {err.get('message', r.text[:200])}")


def _topics(data, n):
    return [
        {"topic": t["queryText"], "searches_7d": t["searchVolume"], "videos": t["videoCount"],
         "popularity": t["popularity"], "daily_7d": t["trend7d"]}
        for t in data.get("topics", [])[:n]
    ]


def search_demand(tc, keyword, language="en"):
    """What people search on TikTok for a keyword (7-day search popularity)."""
    return _topics(tc.get("/v1/searches", keyword=keyword, language=language, limit=10), 10)


def trending_searches(tc, category="all"):
    """Rising search topics on TikTok this week, optionally for one category."""
    return _topics(tc.get("/v1/searches/trending", category=category, limit=15), 15)


def content_gaps(tc, channel="content_gap"):
    """Searches with strong demand and few videos (videos == 0 is a gap)."""
    return _topics(tc.get("/v1/searches/feed", channel=channel, limit=15), 15)


def trending_hashtags(tc, region="US", period="7"):
    """TikTok's trending hashtags chart for a market."""
    data = tc.get("/v1/charts/hashtags", region=region, period=period, limit=15)
    return [
        {"rank": h["rank"], "hashtag": h["name"], "posts": h["posts"], "views": h["views"],
         "popularity_last_day": (h.get("popularity") or [[None, None]])[-1][1]}
        for h in data.get("items", [])
    ]


def top_videos(tc, keyword, region="US"):
    """Most-liked videos posted in the last week for a keyword."""
    data = tc.get("/v1/search/videos", keyword=keyword, sort="most_liked", date="week", region=region, limit=10)
    return [
        {"caption": v["caption"][:140], "views": v["views"], "likes": v["likes"], "shares": v["shares"],
         "creator": v["creator"]["handle"], "followers": v["creator"]["followers"],
         "posted": v["posted"], "url": v["url"]}
        for v in data.get("videos", [])
    ]


def shop_best_sellers(tc, keyword, region="US"):
    """TikTok Shop products ranked by estimated revenue over the last 7 days."""
    data = tc.get("/v1/products/top", keyword=keyword, window="7d", region=region, limit=10)
    return [
        {"product": p["product_title"][:90], "revenue_7d": p["revenue"], "units_7d": p["sale"],
         "price": p["unit_price"], "creators": p["creator_num"], "launched": p["launch_date"],
         "commission": p["commission_rate"]}
        for p in data.get("items", [])
    ]


def pull_snapshot(tc, niche, region):
    """The fixed pipeline: six calls, no model. Useful as a test and as a fallback."""
    return {
        "demand": search_demand(tc, niche),
        "rising_searches": trending_searches(tc),
        "content_gaps": content_gaps(tc),
        "hashtags": trending_hashtags(tc, region),
        "top_videos": top_videos(tc, niche, region),
        "shop_best_sellers": shop_best_sellers(tc, niche, region),
    }


# --- part 2: the agent loop ---
MODEL = os.environ.get("CLAUDE_MODEL", "claude-sonnet-5-5")

TOOLS = [
    {"name": "search_demand",
     "description": "How many people search a keyword on TikTok this week, with related topics. Returns searches_7d (TikTok's 7-day popularity figure, never a monthly count), videos (0 means a content gap) and a daily series.",
     "input_schema": {"type": "object", "properties": {"keyword": {"type": "string"}}, "required": ["keyword"], "additionalProperties": False}},
    {"name": "trending_searches",
     "description": "Rising search topics on TikTok right now. category is one of all, Fashion, Food, Sports, Tourism, Gaming, Science.",
     "input_schema": {"type": "object", "properties": {"category": {"type": "string", "enum": ["all", "Fashion", "Food", "Sports", "Tourism", "Gaming", "Science"]}}, "additionalProperties": False}},
    {"name": "content_gaps",
     "description": "Searches with high demand and few videos. channel is content_gap, or a category: lifestyle, fashion, food, sports, tourism, gaming, science.",
     "input_schema": {"type": "object", "properties": {"channel": {"type": "string", "enum": ["content_gap", "suggested", "lifestyle", "fashion", "food", "sports", "tourism", "gaming", "science"]}}, "additionalProperties": False}},
    {"name": "trending_hashtags",
     "description": "TikTok's trending hashtags in one market over 7, 30 or 90 days, with posts and views.",
     "input_schema": {"type": "object", "properties": {"region": {"type": "string", "description": "US, GB, DE, FR, ES, JP, TH, VN, ID, MY, PH, BR, MX, PL, IT, NL or IE"}, "period": {"type": "string", "enum": ["7", "30", "90"]}}, "additionalProperties": False}},
    {"name": "top_videos",
     "description": "The most-liked videos from the last week for a keyword: caption, views, likes, shares, creator, link.",
     "input_schema": {"type": "object", "properties": {"keyword": {"type": "string"}, "region": {"type": "string"}}, "required": ["keyword"], "additionalProperties": False}},
    {"name": "shop_best_sellers",
     "description": "TikTok Shop products matching a keyword, ranked by estimated revenue over the last 7 days. Use only when the niche sells products.",
     "input_schema": {"type": "object", "properties": {"keyword": {"type": "string"}, "region": {"type": "string"}}, "required": ["keyword"], "additionalProperties": False}},
]
HANDLERS = {f.__name__: f for f in
            (search_demand, trending_searches, content_gaps, trending_hashtags, top_videos, shop_best_sellers)}


def run_tool(tc, name, args):
    try:
        return json.dumps(HANDLERS[name](tc, **args))
    except TokConnectError as exc:           # the model can read this and adjust
        return json.dumps({"error": str(exc)})
    except (TypeError, KeyError) as exc:     # unknown tool or bad arguments
        return json.dumps({"error": f"Bad tool call {name}: {exc}"})


def build_system(niche, region):
    return (
        f"You are a TikTok trend research analyst. Today is {datetime.date.today():%d %B %Y}. "
        f"The reader works in this niche: {niche}. Market: {region}.\n"
        "Use the tools to find what people search for, which searches are rising, which have few videos, "
        "which hashtags and videos are working this week, and (if the niche sells products) what sells on TikTok Shop. "
        "Start with one call per angle, then dig where something is interesting. Stop after at most 12 calls.\n"
        "Write a weekly brief in Markdown: a 2-sentence summary, then sections 'Rising now', 'Content gaps', "
        "'Hashtags and videos', 'Shop' (skip if irrelevant) and 'Three video ideas for this week'. "
        "Quote numbers exactly as the tools return them and call searches_7d a 7-day figure. "
        "Never invent a number or a link. If a tool returns nothing or an error, say so in one line."
    )


def run_agent(tc, niche, region, max_turns=12):
    import anthropic

    client = anthropic.Anthropic()   # reads ANTHROPIC_API_KEY
    messages = [{"role": "user", "content": f"Write this week's TikTok trend brief for: {niche}."}]
    for _ in range(max_turns):
        try:
            response = client.messages.create(
                model=MODEL,
                max_tokens=16000,
                system=build_system(niche, region),
                tools=TOOLS,
                output_config={"effort": "medium"},
                messages=messages,
            )
        except anthropic.AuthenticationError:
            raise SystemExit("Anthropic rejected ANTHROPIC_API_KEY.")
        except anthropic.RateLimitError as exc:
            raise SystemExit(f"Anthropic rate limit; retry in {exc.response.headers.get('retry-after', '60')}s.")
        if response.stop_reason == "refusal":
            raise SystemExit("Claude declined this request.")
        if response.stop_reason == "max_tokens":
            raise SystemExit("Output hit max_tokens; raise it.")
        messages.append({"role": "assistant", "content": response.content})
        calls = [b for b in response.content if b.type == "tool_use"]
        if not calls:                                   # no tool calls: this is the brief
            return "".join(b.text for b in response.content if b.type == "text")
        results = [{"type": "tool_result", "tool_use_id": b.id, "content": run_tool(tc, b.name, b.input)}
                   for b in calls]
        messages.append({"role": "user", "content": results})  # all results in one message
    raise SystemExit("Hit the turn limit before the brief was written.")


# --- part 3: deliver the brief ---
def post_to_slack(text):
    url = os.environ.get("SLACK_WEBHOOK_URL")
    if not url:
        return False
    body = text.replace("**", "*")[:39000]    # Slack mrkdwn uses single asterisks
    requests.post(url, json={"text": body}, timeout=30).raise_for_status()
    return True


def send_email(subject, text):
    host = os.environ.get("SMTP_HOST")
    if not host:
        return False
    msg = EmailMessage()
    msg["Subject"], msg["From"], msg["To"] = subject, os.environ["MAIL_FROM"], os.environ["MAIL_TO"]
    msg.set_content(text)
    with smtplib.SMTP(host, int(os.environ.get("SMTP_PORT", "587"))) as s:
        s.starttls()
        s.login(os.environ["SMTP_USER"], os.environ["SMTP_PASSWORD"])
        s.send_message(msg)
    return True


def main():
    ap = argparse.ArgumentParser(description="Weekly TikTok trend research agent")
    ap.add_argument("mode", choices=["pull", "agent"])
    ap.add_argument("--niche", default="skincare")
    ap.add_argument("--region", default="US")
    ap.add_argument("--max-calls", type=int, default=20)
    args = ap.parse_args()

    key = os.environ.get("TOKCONNECT_API_KEY")
    if not key:
        sys.exit("Set TOKCONNECT_API_KEY (get one at https://app.tokconnect.com/api-key).")
    tc = TokConnect(key, max_calls=args.max_calls)
    try:
        if args.mode == "pull":
            print(json.dumps(pull_snapshot(tc, args.niche, args.region), indent=2))
        else:
            brief = run_agent(tc, args.niche, args.region)
            stamp = f"{datetime.date.today():%Y-%m-%d}"
            os.makedirs("briefs", exist_ok=True)
            with open(f"briefs/{stamp}-{args.niche.replace(' ', '-')}.md", "w") as f:
                f.write(brief)
            print(brief)
            post_to_slack(brief)
            send_email(f"TikTok trend brief: {args.niche} ({stamp})", brief)
    except TokConnectFatal as exc:
        sys.exit(str(exc))
    finally:
        print(f"\n[{tc.credits} TokConnect credits used, {tc.remaining} left]", file=sys.stderr)


if __name__ == "__main__":
    main()
