#!/usr/bin/env python3
"""Comment keyword -> Instagram DM, on Meta's official Instagram API (Instagram Login).

It polls. Comment webhooks need Advanced Access (App Review); polling works on Standard
Access for an account you own, and needs no inbound connection to this machine.

  python3 bot.py --check   read-only: confirm the token, list media, show recent comments
  python3 bot.py           run forever (systemd does this)
"""
import functools
import json
import os
import random
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

HERE = os.path.dirname(os.path.abspath(__file__))
HOST = "https://graph.instagram.com"
API = HOST + "/v27.0"
TOKEN_FILE = os.path.join(HERE, "token")
STATE_FILE = os.path.join(HERE, "state.json")
KEYWORDS_FILE = os.path.join(HERE, "keywords.json")

POLL_SECONDS = 60
MEDIA_WINDOW = 100         # newest N posts/reels watched, in one request. Trials count as posts.
MAX_PAGES = 20             # the comments edge returns 50 per page
MAX_SENDS_PER_SWEEP = 1    # one DM a minute. Meta's documented limit is 750/hour, but see the daily cap
DAILY_CAP_START = 150      # DMs per rolling 24 hours after a first start or a block...
DAILY_CAP_STEP = 50        # ...raised by this much for every day without a block...
DAILY_CAP_MAX = 400        # ...up to this. A sudden jump in volume is what gets an account restricted.
BLOCK_STREAK = 5           # this many sends in a row refused on comments that still exist = a block
BLOCK_PAUSE = 6 * 3600     # then stop sending for this long, keep the queue, and try again
MAX_TRIES = 5
REPLY_WINDOW = 7 * 86400   # Meta: a private reply must go out within 7 days of the comment
TOKEN_REFRESH_AGE = 7 * 86400  # dashboard tokens last 60 days, refresh weekly
RATE_LIMIT_CODES = {4, 17, 32, 613, 80002}


class ApiError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"HTTP {status} code {code}: {message}")
        self.code = code
        self.rate_limited = status == 429 or code in RATE_LIMIT_CODES
        # status 0 = network failure. Codes 1 and 2 are Meta's "try again later".
        self.transient = self.rate_limited or status == 0 or status >= 500 or code in (1, 2)


def log(msg):
    print(msg, flush=True)


def api(token, method, path, params=None, body=None):
    # Never log the URL: it carries the access token.
    if path.startswith("http"):
        url = path  # a paging.next link, already complete
    else:
        url = API + path + "?" + urllib.parse.urlencode({**(params or {}), "access_token": token})
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        try:
            err = json.loads(e.read()).get("error", {})
        except ValueError:
            err = {}
        raise ApiError(e.code, err.get("code"), err.get("message", "no error body")) from None
    except (urllib.error.URLError, TimeoutError) as e:
        raise ApiError(0, None, f"network: {e}") from None


def normalize(text):
    """'DESIGN!! 🙏' -> 'design'. A comment matches only if the whole thing is the keyword."""
    return re.sub(r"[^a-z0-9]", "", text.lower())


def ts(stamp):
    return datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%S%z").timestamp()


def iso(epoch):
    return datetime.fromtimestamp(epoch, timezone.utc).strftime("%Y-%m-%d %H:%M UTC")


def load_json(path, default):
    try:
        with open(path) as f:
            return json.load(f)
    except FileNotFoundError:
        return default


def save_json(path, obj):
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(obj, f)
    os.replace(tmp, path)  # atomic, so a crash mid-write cannot corrupt the state


def shortcode(link):
    """'https://www.instagram.com/reel/Abc123/' -> 'Abc123'. A bare code passes through."""
    m = re.search(r"/(?:reels?|p|tv)/([^/?#]+)", link)
    return m.group(1) if m else link.strip().strip("/")


def load_keywords():
    out = {}
    for k, v in load_json(KEYWORDS_FILE, {}).items():
        if "posts" in v:  # optional: the keyword only works on these posts (links or shortcodes)
            v = {**v, "posts": {shortcode(p) for p in v["posts"]}}
        out[normalize(k)] = v
    return out


def new_comments(call, media_id, mark):
    """Top-level comments at or after `mark`. The edge is newest first, 50 a page."""
    out = []
    page = call("GET", f"/{media_id}/comments", {"fields": "id,text,timestamp,from", "limit": 50})
    for _ in range(MAX_PAGES):
        data = page.get("data", [])
        fresh = [c for c in data if ts(c["timestamp"]) >= mark]
        out += fresh
        nxt = page.get("paging", {}).get("next")
        if not data or len(fresh) < len(data) or not nxt:
            break
        page = call("GET", nxt)
    return out


def exists(call, cid):
    try:
        call("GET", f"/{cid}", {"fields": "id"})
        return True
    except ApiError:
        return False


def pause(state, now):
    """Live comments refused in a row: Instagram has most likely restricted messaging. Stop and lose nothing."""
    for cid, job in state["streak"].items():
        if job["tries"] < MAX_TRIES:  # a comment rides out a few pauses, then is let go, so nothing can jam the queue
            del state["done"][cid]
            state["queue"][cid] = job
            state["people"][job.get("who", "?")] = job["t"]
    state.update(streak={}, paused=now + BLOCK_PAUSE, ramp=now)
    log(f"sends paused until {iso(now + BLOCK_PAUSE)}: {BLOCK_STREAK} refused in a row, "
        f"check Account Status in the Instagram app. {len(state['queue'])} kept in the queue")


def sweep(call, state, keywords, me, now):
    for k, v in (("people", {}), ("sends", []), ("streak", {}), ("paused", 0), ("ramp", now)):
        state.setdefault(k, v)  # added after the first version, so an older state.json still loads

    # 1. Find new keyword comments and queue them.
    media = call("GET", f"/{me['user_id']}/media", {"fields": "id,comments_count,permalink", "limit": MEDIA_WINDOW}).get("data", [])
    # When every keyword is tied to specific posts, the other posts are never fetched.
    scoped = all("posts" in k for k in keywords.values())
    wanted = set().union(*[k["posts"] for k in keywords.values()]) if scoped else None
    watched = {}
    for m in media:
        code = shortcode(m.get("permalink", ""))
        if wanted is not None and code not in wanted:
            continue  # left untracked on purpose: tie a keyword to it later and its comments since install still count
        seen = state["media"].get(m["id"])
        count = m.get("comments_count", 0)
        if seen and seen["count"] == count:
            watched[m["id"]] = seen
            continue
        mark = seen["mark"] if seen else state["since"]
        try:
            comments = new_comments(call, m["id"], mark)
        except ApiError as e:
            log(f"comments fetch failed for media {m['id']}: {e}")
            if seen:
                watched[m["id"]] = seen  # unchanged, so it is retried next sweep
            continue
        for c in comments:
            key = normalize(c.get("text", ""))
            if key not in keywords or c["id"] in state["done"] or c["id"] in state["queue"]:
                continue
            if "posts" in keywords[key] and code not in keywords[key]["posts"]:
                continue
            author = c.get("from", {}).get("username", "?")  # the edge returns from{id,username}, not username
            if author == me["username"]:
                continue
            who = f"{author}:{key}"
            if author != "?" and who in state["people"]:
                continue  # one DM per person per keyword, however many reels they comment it on
            state["people"][who] = ts(c["timestamp"])
            state["queue"][c["id"]] = {"key": key, "t": ts(c["timestamp"]), "tries": 0, "who": who}
            log(f"queued {c['id']} '{key}' from @{author}")
        watched[m["id"]] = {"count": count, "mark": max([ts(c["timestamp"]) for c in comments] + [mark])}
    state["media"] = watched

    # 2. Send, oldest first: a little per check, under the daily cap, and not at all while paused.
    state["sends"] = [t for t in state["sends"] if now - t < 86400]
    cap = min(DAILY_CAP_MAX, DAILY_CAP_START + DAILY_CAP_STEP * int((now - state["ramp"]) // 86400))
    budget = 0 if now < state["paused"] else min(MAX_SENDS_PER_SWEEP, cap - len(state["sends"]))
    sent = failed = 0
    for cid, job in sorted(state["queue"].items(), key=lambda kv: kv[1]["t"]):
        if sent >= budget or failed >= BLOCK_STREAK:  # a bad minute costs a handful of calls, not the whole queue
            break
        cfg = keywords.get(job["key"])
        if cfg is None or now - job["t"] > REPLY_WINDOW:
            del state["queue"][cid]
            state["done"][cid] = {"status": "expired", "t": job["t"]}
            continue
        try:
            call("POST", f"/{me['user_id']}/messages",
                 body={"recipient": {"comment_id": cid}, "message": {"text": cfg["dm"]}})
        except ApiError as e:
            job["tries"] += 1
            failed += 1
            if e.transient and job["tries"] < MAX_TRIES:
                log(f"DM for {cid} failed, will retry ({job['tries']}/{MAX_TRIES}): {e}")
                if e.rate_limited:
                    break
                continue
            log(f"DM for {cid} FAILED for good: {e}")
            del state["queue"][cid]
            state["done"][cid] = {"status": "failed", "t": job["t"]}
            state["people"].pop(job.get("who"), None)  # a later comment from them gets another go
            if exists(call, cid):  # a deleted comment or reel fails too, and says nothing about a block
                state["streak"][cid] = job
                if len(state["streak"]) >= BLOCK_STREAK:
                    pause(state, now)
                    break
            continue
        sent += 1
        state["sends"].append(now)
        state["streak"] = {}
        del state["queue"][cid]
        state["done"][cid] = {"status": "sent", "t": job["t"]}
        log(f"sent DM for {cid} '{job['key']}'")
        if cfg.get("replies"):
            try:
                call("POST", f"/{cid}/replies", body={"message": random.choice(cfg["replies"])})
            except ApiError as e:
                log(f"public reply to {cid} failed (DM already sent): {e}")
    if sent and len(state["sends"]) >= cap:
        log(f"daily cap reached ({cap} in 24 hours), {len(state['queue'])} waiting in the queue")

    state["done"] = {c: d for c, d in state["done"].items() if now - d["t"] < REPLY_WINDOW + 86400}
    state["people"] = {w: t for w, t in state["people"].items() if now - t < REPLY_WINDOW + 86400}


def read_token():
    with open(TOKEN_FILE) as f:
        return f.read().strip()


def refresh_token_if_due(token):
    if time.time() - os.path.getmtime(TOKEN_FILE) < TOKEN_REFRESH_AGE:
        return token
    try:
        # Meta documents this endpoint unversioned, so build the full URL.
        url = HOST + "/refresh_access_token?" + urllib.parse.urlencode(
            {"grant_type": "ig_refresh_token", "access_token": token})
        new = api(token, "GET", url)["access_token"]
    except (ApiError, KeyError) as e:
        log(f"token refresh failed, still using the old one: {e}")
        os.utime(TOKEN_FILE)  # try again in a week, not every sweep
        return token
    fd = os.open(TOKEN_FILE + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        f.write(new)
    os.replace(TOKEN_FILE + ".tmp", TOKEN_FILE)
    log("token refreshed")
    return new


def check(call, me, keywords):
    log(f"token ok: @{me['username']} (id {me['user_id']})")
    for k, v in sorted(keywords.items()):
        log(f"keyword '{k}': {'only on ' + ', '.join(sorted(v['posts'])) if 'posts' in v else 'on all recent posts'}")
    media = call("GET", f"/{me['user_id']}/media", {"fields": "id,comments_count,permalink", "limit": MEDIA_WINDOW}).get("data", [])
    log(f"media visible: {len(media)}")
    if media:
        m = media[0]
        log(f"newest: {m.get('permalink')} ({m.get('comments_count')} comments)")
        for c in new_comments(call, m["id"], time.time() - REPLY_WINDOW)[:5]:
            hit = "MATCH" if normalize(c.get("text", "")) in keywords else "no match"
            log(f"  @{c.get('from', {}).get('username', '?')}: {c.get('text', '')[:60]!r} -> {hit}")


def main():
    token = read_token()
    me = api(token, "GET", "/me", {"fields": "user_id,username"})
    if "--check" in sys.argv:
        check(functools.partial(api, token), me, load_keywords())
        return
    state = load_json(STATE_FILE, None) or {"since": time.time(), "media": {}, "queue": {}, "done": {}}
    log(f"watching @{me['username']}, comments since {iso(state['since'])}")
    while True:
        wait = POLL_SECONDS
        try:
            token = refresh_token_if_due(token)
            sweep(functools.partial(api, token), state, load_keywords(), me, time.time())
        except ApiError as e:
            log(f"sweep failed: {e}")
            if e.rate_limited:
                wait = 300
        save_json(STATE_FILE, state)
        time.sleep(wait)


if __name__ == "__main__":
    main()
