"""lulubanana API client for Python (generated from https://lulubanana.com/api/openapi.json; standard library only).

    from lulubanana import Lulubanana
    lb = Lulubanana("lb_your_key")
    job = lb.create_research_jobs({"niche": "home espresso for students on a budget"})
    while job["data"]["status"] == "planning":   # planning took over 40 s (nothing charged yet): resume it
        time.sleep(30)
        job = lb.create_research_jobs({"plan_job_id": job["data"]["plan_job_id"]})
    done = lb.wait(f"/research/jobs/{job['data']['id']}", until=("completed", "partially_completed", "failed", "canceled"))
    for video in lb.pages(lb.create_search_videos, body={"query": "latte art", "min_outlier_ratio": 3}):
        print(video["url"], video["outlier"]["ratio"])

Every method returns the parsed JSON reply ({"data": ...}); a Markdown reply (format="markdown") is returned as text.
Errors raise LulubananaError with .status and .code.
"""
import json, re, time, urllib.request, urllib.parse, urllib.error

__version__ = "1.0.0"


def _q(v):
    return urllib.parse.quote(str(v), safe="")


def _retry_wait(headers, j, attempt):
    """Seconds to wait before retrying a 429, or None when a retry cannot help (a daily fair-use limit resets within 24 hours)."""
    if j.get("code") == "daily_limit_reached" or re.search(r"daily|a day\b|24 hours", str(j.get("error", "")), re.I):
        return None
    try:
        after = float(headers.get("Retry-After")) if headers and headers.get("Retry-After") else None
    except ValueError:
        after = None
    if after is not None:
        return after if after <= 60 else None
    return min(30, 4 * (attempt + 1))


class LulubananaError(Exception):
    def __init__(self, status, code, message, body=None):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code, self.message, self.body = status, code, message, body


class Lulubanana:
    def __init__(self, api_key, base="https://lulubanana.com/api/v1", timeout=120, max_retries=6):
        self.api_key, self.base, self.timeout, self.max_retries = api_key, base.rstrip("/"), timeout, max_retries
        self.last_credits_used = None
        self.credits_remaining = None

    def _call(self, method, path, query=None, body=None):
        url = self.base + path
        if query:
            url += "?" + urllib.parse.urlencode({k: (str(v).lower() if isinstance(v, bool) else v) for k, v in query.items() if v is not None})
        data = json.dumps(body).encode() if method in ("POST", "PATCH", "PUT") else None
        for attempt in range(self.max_retries + 1):
            req = urllib.request.Request(url, data=data, method=method, headers={"Authorization": "Bearer " + self.api_key, "Content-Type": "application/json", "User-Agent": "lulubanana-python/" + __version__})
            try:
                with urllib.request.urlopen(req, timeout=self.timeout) as r:
                    self.last_credits_used = r.headers.get("X-Credits-Used")
                    self.credits_remaining = r.headers.get("X-Credits-Remaining")
                    raw, ctype = r.read(), (r.headers.get("Content-Type") or "")
                    if ctype and "json" not in ctype.lower():
                        return raw.decode("utf-8")   # e.g. format="markdown": the document itself
                    return json.loads(raw or b"{}")
            except urllib.error.HTTPError as e:
                raw = e.read()
                try:
                    j = json.loads(raw or b"{}")
                except ValueError:
                    j = {}
                wait = _retry_wait(e.headers, j, attempt) if e.code == 429 and attempt < self.max_retries else None
                if wait is not None:
                    time.sleep(wait)
                    continue
                raise LulubananaError(e.code, j.get("code", "error"), j.get("error", str(e)), j)

    def request(self, method, path, query=None, body=None):
        """Call any endpoint by path, e.g. lb.request("GET", "/hooks/types")."""
        return self._call(method.upper(), path, query, body)

    def wait(self, path, until=("completed", "partially_completed", "failed", "canceled"), every=15, timeout=3600):
        """Poll a GET path until data.status is in `until` (or data.finalized is true)."""
        t0 = time.time()
        while True:
            r = self._call("GET", path)
            d = r.get("data") or {}
            if d.get("status") in until or d.get("finalized") is True:
                return r
            if time.time() - t0 > timeout:
                raise TimeoutError(path)
            time.sleep(d.get("poll_after_seconds") or d.get("retry_after_seconds") or every)

    def pages(self, method, *args, body=None, **query):
        """Yield every item of a paged endpoint, following next_cursor (query cursor for GET, body cursor for POST)."""
        cursor = None
        while True:
            if body is not None:
                b = dict(body, **({"cursor": cursor} if cursor else {}))
                r = method(*args, b, **query) if query else method(*args, b)
            else:
                r = method(*args, **dict(query, **({"cursor": cursor} if cursor else {})))
            for item in r.get("data") or []:
                yield item
            cursor = r.get("next_cursor")
            if not cursor:
                return

    def get_account(self):
        """Plan, status and credit balance. Free."""
        return self._call("GET", f"/account", None)

    def get_pricing(self):
        """Credit price of every action (the same as in the app). Free."""
        return self._call("GET", f"/pricing", None)

    def get_usage(self, **query):
        """Credit ledger and 30-day totals. ?limit=1-200 Free."""
        return self._call("GET", f"/usage", query)

    def get_agents(self):
        """Your research agents with their last run. Free."""
        return self._call("GET", f"/agents", None)

    def create_agents(self, body=None):
        """Create an agent and start its first run. Body: {name, brief, terms[3-10], excludes[], platforms["tt","yt","ig"], cadence "once|daily|weekly|monthly", en_only, autopilot}. Costs 100 credits."""
        return self._call("POST", f"/agents", None, body)

    def create_agents_plan(self, body=None):
        """Turn one sentence into a plan (name, search terms, words to filter out). Body: {brief}. Read the plan from GET /jobs/{job_id}. Free."""
        return self._call("POST", f"/agents/plan", None, body)

    def get_agents_item(self, id):
        """One agent, with the done signal: finalized (true once the run and its AI report have stopped), stage, progress_pct, eta_seconds and pending_jobs (each with poll_url and retry_after_seconds). Null fields before finalized mean "not ready", not "nothing found". latest_run_status "failed" means finished but no results. Free."""
        return self._call("GET", f"/agents/{_q(id)}", None)

    def update_agents_item(self, id, body=None):
        """Change name, terms, excludes, platforms, cadence, en_only, autopilot or status ("active" | "paused"). Free."""
        return self._call("PATCH", f"/agents/{_q(id)}", None, body)

    def delete_agents_item(self, id):
        """Delete an agent and its results. Free."""
        return self._call("DELETE", f"/agents/{_q(id)}", None)

    def create_agents_run(self, id, body=None):
        """Start a research run now. If one is already queued or running you get its job back and pay nothing. Costs 100 credits."""
        return self._call("POST", f"/agents/{_q(id)}/run", None, body)

    def get_agents_runs(self, id):
        """The last 30 runs with results and credits charged. Free."""
        return self._call("GET", f"/agents/{_q(id)}/runs", None)

    def get_agents_videos(self, id, **query):
        """Scored videos with hook, hook type, format, length, creator baseline and platform_percentile (rank by views among the same platform here). Filters: ?limit=1-200&min_score=35&min_views=&platform=tt|yt|ig&start_date=&end_date=YYYY-MM-DD&region=US&order_by=score|views|date|reach|platform_percentile&include_transcript=true Free."""
        return self._call("GET", f"/agents/{_q(id)}/videos", query)

    def get_agents_summary(self, id):
        """Everything about an agent in one call: last run, counts, per-platform benchmarks, top 10 organic outliers, winners against the rest, live trends, the AI report and breaking events. Start here. Free."""
        return self._call("GET", f"/agents/{_q(id)}/summary", None)

    def get_agents_report(self, id, **query):
        """The AI report for the latest run (or ?run_id=): key_highlight, themes (why_it_works, tactics, confidence 0-1, evidence_ids), content ideas from viewers' comments, and the sample behind it. Numbers are computed; quote evidence ids. Free."""
        return self._call("GET", f"/agents/{_q(id)}/report", query)

    def get_agents_events(self, id):
        """Breaking events in the niche: a phrase several creators started using in the last 4 days. Title, summary, salience 0-10, the timely keywords autopilot added for 7 days, and evidence videos. Free."""
        return self._call("GET", f"/agents/{_q(id)}/events", None)

    def get_agents_activity(self, id):
        """What autopilot changed and why: replaced search terms, timely keywords from breaking events, weak-term reviews. Free."""
        return self._call("GET", f"/agents/{_q(id)}/activity", None)

    def get_agents_winners(self, id):
        """What separates winners: share of each hook type and format in the top quarter of videos by virality score against the bottom quarter (lift in points). Free."""
        return self._call("GET", f"/agents/{_q(id)}/winners", None)

    def get_agents_compare(self, id):
        """What changed since the previous run: headline numbers, new and dropped videos, the biggest view gains. Free."""
        return self._call("GET", f"/agents/{_q(id)}/compare", None)

    def get_agents_hooks(self, id, **query):
        """Search the opening lines of this agent's videos. ?q=phrase. Tiers: exact, contains, similar; usage_count = videos opening with the same hook. Free."""
        return self._call("GET", f"/agents/{_q(id)}/hooks", query)

    def get_videos_insight(self, id):
        """What set one video apart: key findings in plain sentences plus the numbers behind them. Free."""
        return self._call("GET", f"/videos/{_q(id)}/insight", None)

    def get_agents_playbook(self, id):
        """Hook types and formats ranked by median Virality Score. Free."""
        return self._call("GET", f"/agents/{_q(id)}/playbook", None)

    def get_agents_trends(self, id):
        """Content trends found in this agent's niche. Free."""
        return self._call("GET", f"/agents/{_q(id)}/trends", None)

    def get_trends(self, **query):
        """Trends across your agents. ?kind=content|topic&agent={id} Free."""
        return self._call("GET", f"/trends", query)

    def get_topics(self):
        """Topic trends by region. ?region=GL|US|GB|CA|AU&sort=top|active Free."""
        return self._call("GET", f"/topics", None)

    def get_sounds(self):
        """Trending TikTok sounds: videos using each one now and gained this week, and how many of your videos use it. Free."""
        return self._call("GET", f"/sounds", None)

    def get_tracking_creators(self):
        """Creators you track, with their usual views and breakouts. Free."""
        return self._call("GET", f"/tracking/creators", None)

    def create_tracking_creators(self, body=None):
        """Start tracking a creator. Body: {platform "tt"|"yt", handle}. Charged at each daily check, starting with the first. Costs 15 credits."""
        return self._call("POST", f"/tracking/creators", None, body)

    def delete_tracking_creators_by_platform_by_handle(self, platform, handle):
        """Stop tracking a creator. Free."""
        return self._call("DELETE", f"/tracking/creators/{_q(platform)}/{_q(handle)}", None)

    def get_tracking_creators_by_platform_by_handle(self, platform, handle):
        """A tracked creator: followers, usual views (median of recent posts), breakouts and the latest posts against their usual views. Free."""
        return self._call("GET", f"/tracking/creators/{_q(platform)}/{_q(handle)}", None)

    def get_tracking_videos(self):
        """Videos you track, with daily view counts. Free."""
        return self._call("GET", f"/tracking/videos", None)

    def create_tracking_videos(self, body=None):
        """Start tracking a video. Body: {video_id} from your results, or {url} of a TikTok video. Charged at each daily check, starting with the first. Costs 10 credits."""
        return self._call("POST", f"/tracking/videos", None, body)

    def delete_tracking_videos_item(self, id):
        """Stop tracking a video. Free."""
        return self._call("DELETE", f"/tracking/videos/{_q(id)}", None)

    def get_tracking_videos_item(self, id):
        """A tracked video with its latest numbers and views gained per hour between checks (needs two checks). Free."""
        return self._call("GET", f"/tracking/videos/{_q(id)}", None)

    def get_jobs_item(self, id):
        """Progress and result of a run or a plan. Poll every 15 seconds until finalized is true (for a run: the run and its AI report are both done). status "failed" means finished without results; a failed run is refunded. Free."""
        return self._call("GET", f"/jobs/{_q(id)}", None)

    def get_hooks_types(self):
        """The hook taxonomy with how each type performs across every analysed video: median Virality Score, lift against the typical video, outlier rate (score 35+). Sponsored posts left out. Free."""
        return self._call("GET", f"/hooks/types", None)

    def get_hooks_trending(self, **query):
        """Top-performing opening lines across every analysed video, best Virality Score first; usage_count = videos opening the same way. Sponsored posts left out. Free."""
        return self._call("GET", f"/hooks/trending", query)

    def get_hooks_search(self, **query):
        """Search opening lines across every analysed video (all words must appear). Tiers: exact, contains, similar; best Virality Score first. Free."""
        return self._call("GET", f"/hooks/search", query)

    def get_videos_digest(self, **query):
        """Strongest videos first seen or posted in the last 24-48 hours across everything collected, best Virality Score first. Sponsored posts left out. Free."""
        return self._call("GET", f"/videos/digest", query)

    def get_tiktok_videos_digest(self, **query):
        """Strongest TikTok videos of the last 24-48 hours. Free."""
        return self._call("GET", f"/tiktok/videos/digest", query)

    def get_youtube_videos_digest(self, **query):
        """Strongest YouTube Shorts of the last 24-48 hours. Free."""
        return self._call("GET", f"/youtube/videos/digest", query)

    def get_instagram_videos_digest(self, **query):
        """Strongest Instagram Reels of the last 24-48 hours. Free."""
        return self._call("GET", f"/instagram/videos/digest", query)

    def create_search_videos(self, body=None):
        """Search every video collected so far (scope "library") or only your agents' videos (scope "mine"): keywords in caption, hook, transcript or handle, plus platform, type, language, dates, views, score, follower range and creator-relative outlier ratio. coverage_status says ok, thin or not_collected (start research). Sponsored posts left out unless exclude_sponsored is false. Free."""
        return self._call("POST", f"/search/videos", None, body)

    def create_search_creators(self, body=None):
        """Find creators among everything collected: keywords in their captions or handle, platform, follower range, median views (creators with a checked baseline) and number of outliers (score 35+). Most outliers first. Free."""
        return self._call("POST", f"/search/creators", None, body)

    def get_hashtags(self, **query):
        """Hashtags across every collected video in the window: videos, creators, views, median Virality Score, lift against the typical video, outlier rate. generic=true marks tags like #fyp. Free."""
        return self._call("GET", f"/hashtags", query)

    def get_tiktok_hashtags(self, **query):
        """Top TikTok hashtags: TikTok Creative Center's daily top 100 for the country (rank, posts, views, 7-day curve), or our collected videos when that country has no list. Free."""
        return self._call("GET", f"/tiktok/hashtags", query)

    def get_youtube_hashtags(self, **query):
        """Hashtags on collected YouTube Shorts with their performance. Free."""
        return self._call("GET", f"/youtube/hashtags", query)

    def get_instagram_hashtags(self, **query):
        """Hashtags on collected Instagram Reels with their performance. Free."""
        return self._call("GET", f"/instagram/hashtags", query)

    def get_hashtags_by_hashtag_performance(self, hashtag, **query):
        """One hashtag: TikTok's total videos and views (when checked), its daily Creative Center rank by country, and how it performs in collected videos with the top 10. Free."""
        return self._call("GET", f"/hashtags/{_q(hashtag)}/performance", query)

    def get_topic_trends_regions(self):
        """Regions Topic Trends cover. Free."""
        return self._call("GET", f"/topic-trends/regions", None)

    def get_topic_trends_today(self, **query):
        """Today's topics people talk about in a region (shows, games, people, sports, news), rebuilt every 4 hours, with reach, momentum, outlier Shorts and TikTok videos and reach readings. Free."""
        return self._call("GET", f"/topic-trends/today", query)

    def get_topic_trends_emerging(self, **query):
        """Topics first seen in the last day or growing 20%+ since the reading 18 hours earlier, fastest first. Free."""
        return self._call("GET", f"/topic-trends/emerging", query)

    def get_topic_trends(self, **query):
        """Topics active in a region between two dates (default the last 7 days), biggest first. Free."""
        return self._call("GET", f"/topic-trends", query)

    def get_sounds_trending(self):
        """Trending TikTok sounds with videos using each one now, gained this week, and how many of your videos use it (same as /sounds). Free."""
        return self._call("GET", f"/sounds/trending", None)

    def get_sounds_breakout(self):
        """Sounds growing fastest relative to their size (uses gained since the previous reading). Free."""
        return self._call("GET", f"/sounds/breakout", None)

    def get_sounds_search(self, **query):
        """Find sounds by title or artist: tracked trending sounds, plus sounds heard in collected videos with how those videos perform. Free."""
        return self._call("GET", f"/sounds/search", query)

    def get_sounds_by_sound_id(self, sound_id):
        """One sound: title, artist, videos using it, a playable preview when stored, and how collected videos using it perform. Free."""
        return self._call("GET", f"/sounds/{_q(sound_id)}", None)

    def get_sounds_by_sound_id_usage_history(self, sound_id):
        """Daily count of videos using the sound, one reading a day while it is tracked. Free."""
        return self._call("GET", f"/sounds/{_q(sound_id)}/usage-history", None)

    def get_sounds_by_sound_id_videos(self, sound_id, **query):
        """Collected videos using the sound, best Virality Score first. Free."""
        return self._call("GET", f"/sounds/{_q(sound_id)}/videos", query)

    def get_content_trends(self, **query):
        """Content formats spreading in your agents' niches: the steps, stage (new, rising, accelerating, peaking, declining, evergreen), creators, views and week-on-week change. Trends not seen for 21 days are archived and left out. Free."""
        return self._call("GET", f"/content-trends", query)

    def get_content_trends_item(self, id):
        """One content trend with all its example videos. Free."""
        return self._call("GET", f"/content-trends/{_q(id)}", None)

    def get_agents_slideshows(self, id, **query):
        """This agent's TikTok photo slideshows, best Virality Score first. Free."""
        return self._call("GET", f"/agents/{_q(id)}/slideshows", query)

    def get_agents_ads(self, id):
        """Meta ads found for this agent's search terms, longest-running first among active ones (an ad that keeps running is usually working). Free."""
        return self._call("GET", f"/agents/{_q(id)}/ads", None)

    def get_agents_creators_outliers(self, id, **query):
        """Creators who keep beating their audience in this niche: outliers (score 35+), best and median score, and their best video against their usual views when known. Free."""
        return self._call("GET", f"/agents/{_q(id)}/creators/outliers", query)

    def get_agents_hashtags(self, id, **query):
        """Hashtags in this agent's videos with videos, creators, views, median score, lift against the agent's typical video and outlier rate. Free."""
        return self._call("GET", f"/agents/{_q(id)}/hashtags", query)

    def get_agents_benchmarks(self, id):
        """Genre benchmarks for this agent's niche: median, p75 and p90 views, Virality Score and engagement, by platform, creator size and format. Free."""
        return self._call("GET", f"/agents/{_q(id)}/benchmarks", None)

    def get_agents_sounds(self, id):
        """Sounds used by at least two of this agent's videos, with how those videos perform. Free."""
        return self._call("GET", f"/agents/{_q(id)}/sounds", None)

    def get_agents_affinity(self, id):
        """Beta: hashtags and sounds that go together in this niche (pairs seen in 3+ videos, with lift over chance). Free."""
        return self._call("GET", f"/agents/{_q(id)}/affinity", None)

    def get_agents_trends_latest(self, id):
        """The content trends from this agent's most recent update. Free."""
        return self._call("GET", f"/agents/{_q(id)}/trends/latest", None)

    def get_agents_analysis(self, id, **query):
        """Every AI report written for this agent (one per run), newest first. Read one in full with /agents/{id}/report?run_id=. Free."""
        return self._call("GET", f"/agents/{_q(id)}/analysis", query)

    def get_agents_analysis_latest(self, id):
        """The latest AI report: key highlight, themes with evidence videos and confidence, viewer ideas from comments, breaking events. Free."""
        return self._call("GET", f"/agents/{_q(id)}/analysis/latest", None)

    def get_agents_runs_by_run_id(self, id, run_id):
        """One run: status, stage, videos found, outliers, credits used. Free."""
        return self._call("GET", f"/agents/{_q(id)}/runs/{_q(run_id)}", None)

    def set_agents_autonomy(self, id, body=None):
        """Turn autopilot on or off (it replaces weak search terms and adds timely keywords; every change is listed in /agents/{id}/activity). Free."""
        return self._call("PUT", f"/agents/{_q(id)}/autonomy", None, body)

    def get_tracking_creators_by_platform_by_handle_snapshots(self, platform, handle):
        """A tracked creator's numbers at each check. Free."""
        return self._call("GET", f"/tracking/creators/{_q(platform)}/{_q(handle)}/snapshots", None)

    def get_tracking_creators_by_platform_by_handle_posts(self, platform, handle, **query):
        """This creator's posts we hold, newest first, each against their usual views. Free."""
        return self._call("GET", f"/tracking/creators/{_q(platform)}/{_q(handle)}/posts", query)

    def get_tracking_creators_by_platform_by_handle_posting_cadence(self, platform, handle):
        """How often a tracked creator posts: posts per week, median gap, weekday spread, from the posts seen so far. Free."""
        return self._call("GET", f"/tracking/creators/{_q(platform)}/{_q(handle)}/posting-cadence", None)

    def get_tracking_videos_snapshots(self, id):
        """A tracked video's numbers at each check. Free."""
        return self._call("GET", f"/tracking/videos/{_q(id)}/snapshots", None)

    def get_account_balance(self):
        """Your credit balance. Free."""
        return self._call("GET", f"/account/balance", None)

    def create_account_top_up(self, body=None):
        """A checkout link that adds a credit pack (nothing is charged by this call; whoever opens the link pays). Free."""
        return self._call("POST", f"/account/top-up", None, body)

    def create_webhooks(self, body=None):
        """Add a webhook (or Slack/Discord) for events: digest, alert (breakout video), trend (trend.detected for a new or newly rising trend, trend.stage_changed when a trend moves stage), run (research finished or failed), creator (new post by a tracked creator), analysis (an analysis job finished), search (search.gap_found: a search opportunity job found clear Google or YouTube gaps). Webhook bodies are signed: X-Lulubanana-Signature = sha256 HMAC of the raw body with the secret returned once here. Each delivery has a unique id (X-Lulubanana-Delivery) to de-duplicate retries. Free."""
        return self._call("POST", f"/webhooks", None, body)

    def get_webhooks(self):
        """Your webhooks and their delivery health. Free."""
        return self._call("GET", f"/webhooks", None)

    def get_webhooks_item(self, id):
        """One webhook. Free."""
        return self._call("GET", f"/webhooks/{_q(id)}", None)

    def update_webhooks_item(self, id, body=None):
        """Change a webhook's address, events, or switch it on or off. Free."""
        return self._call("PATCH", f"/webhooks/{_q(id)}", None, body)

    def delete_webhooks_item(self, id):
        """Remove a webhook. Free."""
        return self._call("DELETE", f"/webhooks/{_q(id)}", None)

    def create_webhooks_reenable(self, id, body=None):
        """Switch a webhook back on after it was switched off for 5 failed deliveries in a row. Free."""
        return self._call("POST", f"/webhooks/{_q(id)}/reenable", None, body)

    def create_webhooks_test(self, id, body=None):
        """Send a test event (type "test") within a few seconds; see the result in /webhooks/{id}/deliveries. Free."""
        return self._call("POST", f"/webhooks/{_q(id)}/test", None, body)

    def get_webhooks_deliveries(self, id, **query):
        """Recent deliveries (kept 30 days) with your server's reply status; failed ones can be sent again. Free."""
        return self._call("GET", f"/webhooks/{_q(id)}/deliveries", query)

    def create_webhooks_deliveries_by_delivery_id_retry(self, delivery_id, body=None):
        """Send one delivery again (same payload, a new delivery id that names the original in retry_of). Free."""
        return self._call("POST", f"/webhooks/deliveries/{_q(delivery_id)}/retry", None, body)

    def create_videos_batch(self, body=None):
        """Up to 50 full video records in one call, duplicates removed; ids not found come back as {id, found:false}. Free."""
        return self._call("POST", f"/videos/batch", None, body)

    def get_videos_item(self, id):
        """One video's full record: stats (missing ones are null, never zero), creator baseline and outlier ratio, hook, format, transcript, on-screen analysis, analysis_status (frames, transcript, caption_only), likely_repost (true only when an earlier post by a different creator in our database has the same caption of 6+ words or the same opening line; false when none was found; null when it cannot be told; with likely_repost_reason and repost_of) and provenance that separates observed numbers from AI readings. Free."""
        return self._call("GET", f"/videos/{_q(id)}", None)

    def get_videos_metrics(self, id):
        """A video's readings over time (tracking checks and research runs) with its age at each, and views per hour and per day when there are two readings. Free."""
        return self._call("GET", f"/videos/{_q(id)}/metrics", None)

    def create_research_jobs(self, body=None):
        """Start a full niche research in one call: send a niche sentence (search terms are planned for you, free) or your own terms, or an agent_id to run again. Costs one research run, like the app; a failed run is refunded and a canceled queued job is refunded. When planning takes longer than 40 s the reply is status "planning" with a plan_job_id: send {"plan_job_id"} again (the rest of the request is kept); a plan starts one job, so sending it again returns that job without a new charge. Poll /research/jobs/{id} every 15 s; statuses: queued, collecting, analyzing, completed, partially_completed, fail Costs 100 credits."""
        return self._call("POST", f"/research/jobs", None, body)

    def get_research_jobs(self, **query):
        """Your research jobs, newest first, with their status. Free."""
        return self._call("GET", f"/research/jobs", query)

    def create_research_jobs_batch(self, body=None):
        """Start 1-5 research jobs in one call (each item is a POST /research/jobs body: niche, terms or agent_id). Costs one research run per job (100 credits each); all or nothing: the balance (and the key's monthly limit) must cover the whole batch, and every job starts in one transaction, or none does. A run already going for an agent is returned free. Missing terms are planned for free (up to 40 s; else status planning with plan_job_ids to send back, nothing charged). Costs 100 credits."""
        return self._call("POST", f"/research/jobs/batch", None, body)

    def get_research_jobs_item(self, id):
        """One research job's status. Poll every 15 seconds until completed, partially_completed, failed or canceled. Free."""
        return self._call("GET", f"/research/jobs/{_q(id)}", None)

    def create_research_jobs_cancel(self, id, body=None):
        """Cancel a job that has not started collecting yet; its credits come back. A canceled scheduled run skips that occurrence: the schedule continues with the next one. A job already collecting finishes on its own. Free."""
        return self._call("POST", f"/research/jobs/{_q(id)}/cancel", None, body)

    def get_research_jobs_results(self, id, **query):
        """Everything a finished job found: coverage (videos per platform, outliers, off-topic filtered, per-term results, coverage_status), freshness, credits charged and cache reuse, top videos with creator-relative outlier ratios, the AI report, what changed since the previous run, and new_since_previous: the outliers, trends (and trend stage changes) and opportunities (new report themes and ideas, search opportunities) that the agent's previous finished run did not have. ?format=markdown answers one Markdown document (text/markdown). Free."""
        return self._call("GET", f"/research/jobs/{_q(id)}/results", query)

    def get_research_schedules(self):
        """Your recurring research (agents on a schedule). Free."""
        return self._call("GET", f"/research/schedules", None)

    def create_research_schedules(self, body=None):
        """Start recurring research: daily, weekly, monthly or every N days (2-90). The first run starts now; each run costs one research run, like the app. Costs 100 credits."""
        return self._call("POST", f"/research/schedules", None, body)

    def update_research_schedules_item(self, id, body=None):
        """Pause or resume (status "paused" | "active"), change cadence or every_days (null clears it), terms, platforms or autopilot. Free."""
        return self._call("PATCH", f"/research/schedules/{_q(id)}", None, body)

    def get_formats(self, **query):
        """Creative formats (tutorial, GRWM, review, haul, transition, talking head, faceless) across independent creators: performance distribution, lift, outlier rate, cross-creator adoption by week, growth, lifecycle (new, rising, steady, evergreen, declining) and confidence. For AI-described structures see /content-trends. Free."""
        return self._call("GET", f"/formats", query)

    def get_formats_by_format(self, format, **query):
        """One format in depth: the same numbers as /formats plus which hook types and hashtags work best with it, results per platform and the 12 strongest examples. Free."""
        return self._call("GET", f"/formats/{_q(format)}", query)

    def create_formats_match(self, body=None):
        """Which formats and hook types work for a topic: matches collected videos by words, ranks formats by lift over the typical video, with independent creators and an example each. coverage_status says when there is too little data. Free."""
        return self._call("POST", f"/formats/match", None, body)

    def get_creators_by_platform_by_handle(self, platform, handle):
        """One creator: followers, baseline (median views of recent posts, breakouts 3x+, outlier frequency, confidence), collected videos and their scores, strongest formats, hook types and hashtags, top and recent videos. Free."""
        return self._call("GET", f"/creators/{_q(platform)}/{_q(handle)}", None)

    def create_creators_compare(self, body=None):
        """Compare 2-10 creators side by side, with rankings by median score, outlier frequency, median views and engagement. Free."""
        return self._call("POST", f"/creators/compare", None, body)

    def create_watchlists(self, body=None):
        """Group creators and videos to watch (competitors, a niche, a campaign). Creating a list is free; track:true also starts daily tracking at the app's price per check. Free."""
        return self._call("POST", f"/watchlists", None, body)

    def get_watchlists(self):
        """Your watchlists. Free."""
        return self._call("GET", f"/watchlists", None)

    def get_watchlists_item(self, id):
        """A watchlist with each creator's usual views, change since the previous check and latest posts against it (new_outliers = 3x+), and each video's numbers and views per hour. Free."""
        return self._call("GET", f"/watchlists/{_q(id)}", None)

    def update_watchlists_item(self, id, body=None):
        """Rename a watchlist. Free."""
        return self._call("PATCH", f"/watchlists/{_q(id)}", None, body)

    def delete_watchlists_item(self, id):
        """Delete a watchlist (tracking of its items continues until you stop it). Free."""
        return self._call("DELETE", f"/watchlists/{_q(id)}", None)

    def create_watchlists_items(self, id, body=None):
        """Add creators or videos to a watchlist (track:true also starts daily tracking at the app's price). Free."""
        return self._call("POST", f"/watchlists/{_q(id)}/items", None, body)

    def create_watchlists_items_remove(self, id, body=None):
        """Remove creators or videos from a watchlist (their tracking continues until you stop it). Free."""
        return self._call("POST", f"/watchlists/{_q(id)}/items/remove", None, body)

    def get_account_audit(self, **query):
        """Every API request made with your keys in the last 90 days: when, which key, method, path, result status and credits. Free."""
        return self._call("GET", f"/account/audit", query)

    def get_analysis_jobs_item(self, id):
        """Status and result of an analysis job (opportunities, comments, comment insights, creator baseline, creative breakdown, content briefs, hook recommendations, and the search jobs: intent, demand, Google and YouTube results audits, search opportunities). Poll every 10 s until completed or failed (a search opportunity job waiting for its research run says collecting: poll every minute). A failed paid check is refunded. Free."""
        return self._call("GET", f"/analysis/jobs/{_q(id)}", None)

    def create_profiles(self, body=None):
        """Save an audience and content profile (niche, audience, interests, problems, market, language, tone, formats, exclusions, constraints, outcomes; a product is optional) to match opportunities against. Free."""
        return self._call("POST", f"/profiles", None, body)

    def get_profiles(self):
        """Your audience profiles. Free."""
        return self._call("GET", f"/profiles", None)

    def get_profiles_item(self, id):
        """One profile. Free."""
        return self._call("GET", f"/profiles/{_q(id)}", None)

    def update_profiles_item(self, id, body=None):
        """Change a profile (send only the fields to change). Free."""
        return self._call("PATCH", f"/profiles/{_q(id)}", None, body)

    def delete_profiles_item(self, id):
        """Delete a profile. Free."""
        return self._call("DELETE", f"/profiles/{_q(id)}", None)

    def create_opportunities_discover(self, body=None):
        """Ranked, audience-matched content opportunities grounded in videos that really outperformed: candidates come from your research (winning themes, viewer requests, outlier clusters, format trends) and topics in your market; irrelevant viral content is rejected with a reason. Each has opportunity_score (0-100, weighted factors) and a separate evidence confidence, source video links, hook mechanism, structure, angle, format, key information, payoff and originality requirements. Async: poll /analysis/jobs/{job_id} (about 1 minute). Included, up to 10 a day. Free."""
        return self._call("POST", f"/opportunities/discover", None, body)

    def create_opportunities_score(self, body=None):
        """Score your own candidate ideas against a profile, with evidence from the video ids you attach (ideas without evidence get low confidence, never "verified"). Async like discover. Included, shares the 10-a-day limit. Free."""
        return self._call("POST", f"/opportunities/score", None, body)

    def get_opportunities(self, **query):
        """Opportunities found for you, newest first. ?verified=true keeps only verified winners. Free."""
        return self._call("GET", f"/opportunities", query)

    def get_opportunities_item(self, id):
        """One opportunity with all its evidence and creative intelligence. Free."""
        return self._call("GET", f"/opportunities/{_q(id)}", None)

    def create_opportunities_reject(self, id, body=None):
        """Reject an opportunity: it and similar topics stop being suggested (feedback for your ranking). Free."""
        return self._call("POST", f"/opportunities/{_q(id)}/reject", None, body)

    def get_hooks_mechanisms(self, **query):
        """Psychological mechanisms behind strong hooks (curiosity, mistake avoidance, contrarian, surprising fact, problem-solution, before-after, story, comparison, challenge, question, social proof, demonstration, listicle, suspense, humor) with how hooks using each perform against the other strong hooks. Free."""
        return self._call("GET", f"/hooks/mechanisms", query)

    def get_hooks_formulas(self, **query):
        """Hook formulas repeated by several independent creators (structure, not wording), with how they perform and examples. Free."""
        return self._call("GET", f"/hooks/formulas", query)

    def get_hooks_emerging(self, **query):
        """Hook mechanisms and formulas that are being used more often lately (last 21 days against the 42 before) by several creators. Free."""
        return self._call("GET", f"/hooks/emerging", query)

    def get_videos_similar(self, id, **query):
        """Videos most similar in meaning (caption and hook) to this one, with a similarity from 0 to 1. Free."""
        return self._call("GET", f"/videos/{_q(id)}/similar", query)

    def create_hooks_evaluate(self, body=None):
        """Test a proposed opening line against similar hooks that were really published: how they performed against the typical video, their likely mechanisms and the closest examples. Evidence, not a prediction. Free."""
        return self._call("POST", f"/hooks/evaluate", None, body)

    def get_videos_comments(self, id):
        """The top public comments we hold for a video (text and likes; no commenter names). Free."""
        return self._call("GET", f"/videos/{_q(id)}/comments", None)

    def create_videos_comments_collect(self, id, body=None):
        """Collect a video's top public comments (then comment insights run by themselves, within the 30-a-day comment analyses). TikTok costs one video check, like the app; YouTube is free (up to 60 collections a day); anything collected in the last 7 days is free. Refunded if it fails or finds none. Costs 10 credits."""
        return self._call("POST", f"/videos/{_q(id)}/comments/collect", None, body)

    def get_videos_comments_intelligence(self, id):
        """What viewers say: clusters of questions, problems, frustrations, objections, tutorial and comparison requests, buying or booking intent, requests for alternatives, with counts, shares, quoted evidence and confidence; unanswered questions and content gaps. Starts the analysis when comments are held (included, 30 a day; a read-only key gets status not_started instead). Free."""
        return self._call("GET", f"/videos/{_q(id)}/comments/intelligence", None)

    def get_agents_audience(self, id):
        """Audience intelligence across an agent's videos: recurring questions, problems, requests and intent with how many videos they appear on, unanswered questions, and the report's viewer ideas. Free."""
        return self._call("GET", f"/agents/{_q(id)}/audience", None)

    def get_agents_gaps(self, id):
        """Under-served content: questions and requests from viewers (comment insights and the report) that few collected videos cover. Free."""
        return self._call("GET", f"/agents/{_q(id)}/gaps", None)

    def create_creators_baseline(self, body=None):
        """Measure a creator's normal: their last ~30 posts -> median and mean views, 3x+ breakouts, like rate. Costs one creator check, like the app; free when this creator was measured in the last 24 hours; refunded if it fails. Async: poll /analysis/jobs/{job_id}. Costs 15 credits."""
        return self._call("POST", f"/creators/baseline", None, body)

    def create_videos_outlier_check(self, body=None):
        """Is this video an outlier for its own creator? Compares its views with the creator's recent posts: outlier ratio, class (normal, above_average 1.5x, viral_outlier 3x, strong_breakout 10x, exceptional_breakout 25x), age-matched baseline when enough posts are of similar age, percentile, engagement lift, sample size and confidence, and likely_repost (true only when an earlier post by a different creator has the same caption of 6+ words or the same opening line; null when it cannot be told). Costs one creator check (free within 24 hours of the last one for that creator; refunded if it fails). Costs 15 credits."""
        return self._call("POST", f"/videos/outlier-check", None, body)

    def create_videos_analyze(self, id, body=None):
        """Frame-level creative breakdown of the video itself: frames (dense in the first 3 s), on-screen text, measured cuts and the transcript are read by a vision model into hook (spoken and on-screen opening, first frame, categories, mechanism, curiosity gap, promise, problem, tone), opening -> body -> payoff -> ending structure, visual presentation, storytelling techniques and a mechanism hypothesis, with timestamped evidence and confidence. Done once per video and shared. Included, 20 a day. If the video cannot be fetched the status says incomplete: a caption is never passed off as video analysis. Free."""
        return self._call("POST", f"/videos/{_q(id)}/analyze", None, body)

    def get_videos_analysis(self, id):
        """The creative breakdown of a video, or its status (not_analysed, incomplete with the reason). Free."""
        return self._call("GET", f"/videos/{_q(id)}/analysis", None)

    def get_videos_breakouts_early(self, **query):
        """Videos still gaining fast relative to their creator's normal (from two or more readings by your agents' runs or tracking): views per day, ratio now, an early_breakout flag and confidence. Free."""
        return self._call("GET", f"/videos/breakouts/early", query)

    def get_formats_transfer(self, **query):
        """Cross-platform format transfer: how each format performs against each platform's own typical video, and where a proven format is still rare (a chance to bring it over). Free."""
        return self._call("GET", f"/formats/transfer", query)

    def get_alerts_settings(self):
        """Alert thresholds: breakout alerts fire when a tracked creator's post reaches breakout_ratio x their usual views (default 3). Free."""
        return self._call("GET", f"/alerts/settings", None)

    def set_alerts_settings(self, body=None):
        """Change alert settings: breakout_ratio (1.5-50), breakout_alerts, trend_alerts, email_alerts. Webhooks receive the same events (subscribe in /webhooks). Free."""
        return self._call("PUT", f"/alerts/settings", None, body)

    def create_search_intent_extract(self, body=None):
        """What people search on Google and YouTube about a topic, niche, audience or up to 20 of your videos: topics, entities named in the videos, viewer questions (from comments, or marked as hypotheses), Google and YouTube queries with intent (informational, commercial, comparison, tutorial, navigational, local) and groups, ambiguous terms, related keywords, adjacent niches and the source videos used (without video_ids: 3+ collected videos that name the topic's distinctive words, else the topic alone, said in limitations). Queries are AI suggestions: check their demand with POST /search/demand. Async Free."""
        return self._call("POST", f"/search/intent-extract", None, body)

    def get_search_intents(self, **query):
        """Your search intent extractions, newest first (counts only; read one for the queries). Free."""
        return self._call("GET", f"/search/intents", query)

    def get_search_intents_item(self, id):
        """One search intent extraction: topics, entities, viewer questions, Google and YouTube queries with intent and groups, ambiguous terms, related keywords, adjacent niches, sources. Free."""
        return self._call("GET", f"/search/intents/{_q(id)}", None)

    def create_search_demand(self, body=None):
        """Search demand for 1-20 keywords: Google monthly searches, cost per click, advertiser competition and 12 months of history (Google Ads keyword data), 3-month growth, Google Trends web and YouTube interest (daily, last 3 months) with the last 4 weeks against the 4 before, related queries, a momentum label, granularity, geography, date range and confidence. YouTube search volume is null (not published by Google). 10 credits per lookup; free when every keyword was looked up in the last 7 days (up to 100 free lookups a day); returned if it fails. Async: poll /analysis/jobs/{job_id}. Markets: US, GB Costs 10 credits."""
        return self._call("POST", f"/search/demand", None, body)

    def get_search_demand(self, **query):
        """Stored search demand for one keyword you looked up (with POST /search/demand, or as one of your search opportunities' searches); no new lookup: the same fields as POST /search/demand, with stored, fresh (looked up in the last 7 days) and snapshots (your live lookups). A keyword you have not looked up: every field null, with the reasons in missing and how to look it up. Free."""
        return self._call("GET", f"/search/demand", query)

    def create_search_google_serp_audit(self, body=None):
        """Audit Google's page one for 1-5 keywords: the top results (title, link, site, date, snippet, page features), people also ask and related searches, then an audit from titles, snippets and dates (pages are not opened): intent match, answer completeness, outdated results, missing formats (comparison, tutorial, demonstration, explanation), weaknesses, unanswered questions, difficulty 0-100 with why, and gap_score 0-100. 10 credits per keyword not fetched in the last 7 days (cached keywords are free, up to 100 free audits a day); a keyword that fails is refunded. Async: poll /analysis/jobs/{job_id} Costs 10 credits."""
        return self._call("POST", f"/search/google-serp-audit", None, body)

    def create_search_youtube_serp_audit(self, body=None):
        """Audit YouTube's top 20 for 1-5 keywords: title, link, channel, views, published, duration, Shorts or not; then freshness (median age), outdated tutorials, undercovered viewer questions, recommended long-form angles, weaknesses, difficulty 0-100 and gap_score 0-100, from titles, descriptions, dates and views (videos are not watched). 10 credits per keyword not fetched in the last 7 days (cached keywords are free, up to 100 free audits a day); a keyword that fails is refunded. Async: poll /analysis/jobs/{job_id}, or read /search/serp-audits/{job_id}. Costs 10 credits."""
        return self._call("POST", f"/search/youtube-serp-audit", None, body)

    def get_search_serp_audits_item(self, id):
        """One Google or YouTube results audit (id sau_...) that you requested, or every audit of one of your audit or search-opportunity jobs (send the job id). Results, people also ask, related searches, page features and the audit with its difficulty, gap score, factors and limitations. Free."""
        return self._call("GET", f"/search/serp-audits/{_q(id)}", None)

    def create_search_opportunities(self, body=None):
        """The flagship search opportunity research: social evidence (verified organic outliers in your agent's videos, or the whole library: videos that name the niche's distinctive words and are close to it in meaning, English only, in the window) -> topics and audience problems from the outliers, hooks, formats and comment questions -> Google and YouTube searches per topic -> demand (one Google Ads keyword lookup for all, Google Trends web and YouTube for the top max_keywords) -> Google and YouTube results audits (7-day cache) -> four separate 0-100 scores (social, google_seo, youtube, evidence_confid Costs 100 credits."""
        return self._call("POST", f"/search/opportunities", None, body)

    def get_search_opportunities(self, **query):
        """Your search opportunities, newest job first, each job in rank order, with every field (sources, hooks, queries, demand, competition, gaps, angle, format, the four scores with factors, timing, verified, hypotheses, limitations). ?job_id= adds that job's status, and why it returned fewer than asked. Free."""
        return self._call("GET", f"/search/opportunities", query)

    def get_search_opportunities_item(self, id):
        """One search opportunity with all its evidence, scores, factors and the score formulas. Free."""
        return self._call("GET", f"/search/opportunities/{_q(id)}", None)

    def create_search_opportunities_reject(self, id, body=None):
        """Reject a search opportunity (feedback): similar topics stop being suggested. Free."""
        return self._call("POST", f"/search/opportunities/{_q(id)}/reject", None, body)

    def create_briefs_generate(self, body=None):
        """A content brief for one of your opportunities (opp_... from /opportunities or sop_... from /search/opportunities): title options, hook approaches grounded in real hooks (each links the videos it comes from), an outline with beats or sections, on-screen text ideas, a call to action, why it fits the audience, the viewer questions it answers, sources, and verified findings (measured) kept apart from hypotheses (AI-written). format short, long or article (default: the opportunity's recommended format); tone and a profile_id are optional. Async: poll /analysis/jobs/{job_id} (about a minute), then r Free."""
        return self._call("POST", f"/briefs/generate", None, body)

    def get_briefs(self, **query):
        """Your content briefs, newest first. Free."""
        return self._call("GET", f"/briefs", query)

    def get_briefs_item(self, id, **query):
        """One content brief (brf_... id, or the job id from POST /briefs/generate): JSON with every part and a markdown field; ?format=markdown answers the Markdown document itself (text/markdown). Free."""
        return self._call("GET", f"/briefs/{_q(id)}", query)

    def create_hooks_recommend(self, body=None):
        """Hook mechanisms for an audience (a saved profile, or audience text and an optional niche), ranked by measured lift: for each mechanism the hooks, independent creators, median virality score, lift over the other strong hooks, outlier rate, confidence and real example hooks with links to their videos, matched to the audience by the niche's distinctive words together with meaning (the whole library when fewer than 12 match, said in limitations), plus templates adapted to the audience (hypotheses, each pointing at the real hook it adapts). Async: poll /analysis/jobs/{job_id} (about a minute). Incl Free."""
        return self._call("POST", f"/hooks/recommend", None, body)

    def create_estimate(self, body=None):
        """Cost estimate before you spend: send up to 20 calls ({method, path, body}) and get each one's credits, why it is free when it is (cached in the last 7 days, already running, a read, included), the fair use left today for included AI work, the total, your balance and whether it covers the total. Changes nothing and charges nothing. Free."""
        return self._call("POST", f"/estimate", None, body)
