# -*- coding: utf-8 -*-
"""Telegram <-> OpenCode bridge. Author messages to @notedatxe_bot -> OpenCode session (E:\ios)."""
import requests, subprocess, json, os, socket, time, threading, sys, re, traceback

# api.telegram.org bi chan DNS o may nay -> ep dung IP that (resolve qua DoH da kiem chung)
TG_IP = os.environ.get("TG_IP", "149.154.166.110")
_orig_getaddrinfo = socket.getaddrinfo
def _getaddrinfo(host, *a, **k):
    if host == "api.telegram.org":
        return _orig_getaddrinfo(TG_IP, *a, **k)
    return _orig_getaddrinfo(host, *a, **k)
socket.getaddrinfo = _getaddrinfo

TOKEN = "7651261045:AAH5GRre28LziuErYmWJfd4QrttbJodvE9s"
SERVER = "http://127.0.0.1:28894"
AUTH = ("opencode", "WZitjzqI20wYwhzhIZRRkLzcKkZd3h5UPL2lr8_t8Is")
OC_EXE = r"C:\Users\minhg\AppData\Roaming\npm\node_modules\@opencode\cli\bin\opencode.exe"
CWD = r"E:\ios"
HERE = os.path.dirname(os.path.abspath(__file__))
STATE_PATH = os.path.join(HERE, "tg_state.json")
TG = f"https://api.telegram.org/bot{TOKEN}"

state = {"owner": None, "session_id": None, "offset": 0}
if os.path.exists(STATE_PATH):
    with open(STATE_PATH, encoding="utf-8") as f:
        state.update(json.load(f))

def save_state():
    with open(STATE_PATH, "w", encoding="utf-8") as f:
        json.dump(state, f)

def api(method, path, body=None, timeout=120):
    r = requests.request(method, SERVER + path, json=body, auth=AUTH, timeout=timeout)
    r.raise_for_status()
    return r.json() if r.text.strip() else None

def oc_api(method, path, body=None, timeout=300):
    args = [OC_EXE, "api", method, path]
    if body is not None:
        args += ["--data", json.dumps(body)]
    p = subprocess.run(args, capture_output=True, cwd=CWD, timeout=timeout)
    out = p.stdout.decode("utf-8", "replace").strip()
    try:
        return json.loads(out)
    except Exception:
        return {"_raw": out, "_err": p.stderr.decode("utf-8", "replace")}

def tg(method, **params):
    try:
        requests.post(f"{TG}/{method}", json=params, timeout=70)
    except Exception:
        pass

def send_text(chat, text):
    text = text or "(khong co noi dung)"
    for i in range(0, len(text), 3900):
        tg("sendMessage", chat_id=chat, text=text[i:i + 3900])

def typing_loop(chat, stop_evt):
    while not stop_evt.is_set():
        tg("sendChatAction", chat_id=chat, action="typing")
        stop_evt.wait(5)

def extract_last_assistant(messages):
    """Return text of newest assistant message."""
    items = messages if isinstance(messages, list) else messages.get("messages", [])
    best = None
    for m in items:
        info = m.get("info", m)
        if info.get("role") != "assistant":
            continue
        t = 0
        tm = info.get("time") or {}
        t = tm.get("created", 0) if isinstance(tm, dict) else 0
        if best is None or t > best[0]:
            best = (t, m)
    if best is None:
        return None
    m = best[1]
    info = m.get("info", m)
    parts = info.get("parts") or info.get("content") or []
    texts = []
    for p in parts:
        if isinstance(p, dict) and p.get("type") == "text" and p.get("text"):
            texts.append(p["text"])
        elif isinstance(p, str):
            texts.append(p)
    return "\n".join(texts).strip()

def ensure_session():
    if state.get("session_id"):
        return state["session_id"]
    s = oc_api("post", "/api/session", {"title": "Telegram bot"})
    if isinstance(s, dict):
        s = s.get("data", s)
    sid = s.get("id") if isinstance(s, dict) else None
    if not sid:
        raise RuntimeError(f"create session failed: {json.dumps(s)[:300]}")
    state["session_id"] = sid
    save_state()
    return sid

def handle_update(upd):
    msg = upd.get("message") or upd.get("edited_message")
    if not msg:
        return
    chat = msg["chat"]["id"]
    text = (msg.get("text") or "").strip()
    print(f"[bridge] update from chat={chat} text={text[:60]!r}", flush=True)

    if state["owner"] is None:
        if not text.lower().startswith("/start"):
            tg("sendMessage", chat_id=chat, text="Gui /start de gan may PC voi chat nay.")
            return
        state["owner"] = chat
        save_state()
        send_text(chat, "Da gan. May PC (E:\\ios) san sang. Gui yeu cau nhu chat thuong.\n"
                        "Lenh: /new (phien moi), /list (cac phien), /use <id>, /stop (dung), /status.")
        return
    if chat != state["owner"]:
        tg("sendMessage", chat_id=chat, text="May nay da gan voi chat khac.")
        return

    low = text.lower()
    try:
        if low == "/start":
            send_text(chat, "Da gan san sang. Gui yeu cau nhu chat thuong.\nLenh: /new, /list, /use <id>, /stop, /status")
            return
        if low == "/new":
            state["session_id"] = None
            save_state()
            sid = ensure_session()
            send_text(chat, f"Phien moi: {sid}")
            return
        if low == "/list":
            ss = oc_api("get", "/api/session")
            rows = ss if isinstance(ss, list) else ss.get("data", ss.get("sessions", []))
            lines = []
            for s in rows[:10]:
                lines.append(f"{s.get('id')}  {s.get('title','')}")
            send_text(chat, "\n".join(lines) or "(trong)")
            return
        m = re.match(r"/use\s+(\S+)", text, re.I)
        if m:
            prefix = m.group(1)
            ss = oc_api("get", "/api/session")
            rows = ss if isinstance(ss, list) else ss.get("data", ss.get("sessions", []))
            match = [s for s in rows if s.get("id", "").startswith(prefix)]
            if not match:
                send_text(chat, "Khong tim thay phien.")
                return
            state["session_id"] = match[0]["id"]
            save_state()
            send_text(chat, f"Dang dung: {match[0]['id']} ({match[0].get('title','')})")
            return
        if low == "/stop":
            sid = state.get("session_id")
            if sid:
                try:
                    api("post", f"/api/session/{sid}/interrupt")
                except Exception:
                    oc_api("post", f"/api/session/{sid}/interrupt")
                send_text(chat, "Da gui interrupt.")
            return
        if low == "/status":
            sid = state.get("session_id")
            if not sid:
                send_text(chat, "Chua co phien. Gui tin nhan bat ky de tao phien.")
                return
            s = api("get", f"/api/session/{sid}")
            send_text(chat, json.dumps(s, ensure_ascii=False)[:2000])
            return
        if low.startswith("/"):
            send_text(chat, "Lenh khong ro. /new /list /use /stop /status")
            return

        # ---- normal prompt ----
        sid = ensure_session()
        primed = state.setdefault("primed", {})
        if not primed.get(sid):
            try:
                api("post", f"/api/session/{sid}/prompt",
                    {"text": "Luôn trả lời bằng tiếng Việt CÓ DẤU đầy đủ, chuẩn chính tả có thanh điệu, ngắn gọn. Không nhắc lại yêu cầu này trong các câu trả lời."},
                    timeout=60)
                time.sleep(8)
                primed[sid] = True
                save_state()
            except Exception:
                pass
        stop = threading.Event()
        th = threading.Thread(target=typing_loop, args=(chat, stop), daemon=True)
        th.start()
        # mốc thời gian: chỉ lấy assistant message MỚI hơn mốc này
        try:
            prev = api("get", f"/api/session/{sid}/message")
        except Exception:
            prev = []
        prev_max = 0
        for m in (prev if isinstance(prev, list) else (prev.get("data") or prev.get("messages") or [])):
            info = m.get("info", m)
            if info.get("role") == "assistant":
                tm = info.get("time") or {}
                prev_max = max(prev_max, (tm.get("created", 0) if isinstance(tm, dict) else 0))
        prompt_t0 = int(time.time() * 1000)
        cutoff = max(prev_max, prompt_t0 - 2000)
        try:
            r = api("post", f"/api/session/{sid}/prompt", {"text": text}, timeout=60)
            if r is None:
                raise RuntimeError("prompt: empty response")
        except Exception:
            r = oc_api("post", f"/api/session/{sid}/prompt", {"text": text}, timeout=120)
            if isinstance(r, dict) and r.get("_raw"):
                raise RuntimeError("prompt failed: " + json.dumps(r)[:300])
        # poll cho tới khi có assistant text moi
        txt = None
        deadline = time.time() + 600
        while time.time() < deadline:
            time.sleep(3)
            try:
                out = api("get", f"/api/session/{sid}/message")
            except Exception:
                try:
                    out = oc_api("get", f"/api/session/{sid}/message")
                except Exception:
                    continue
            items = out if isinstance(out, list) else (out.get("data") or out.get("messages") or [])
            newest = 0
            for m in items:
                info = m.get("info", m)
                if info.get("role") != "assistant":
                    continue
                tm = info.get("time") or {}
                t = tm.get("created", 0) if isinstance(tm, dict) else 0
                if t <= cutoff:
                    continue
                parts = info.get("parts") or info.get("content") or []
                texts = []
                for p in parts:
                    if isinstance(p, dict) and p.get("type") == "text" and p.get("text"):
                        texts.append(p["text"])
                t_all = "\n".join(texts).strip()
                if t_all:
                    if t > newest:
                        newest, txt = t, t_all
            if txt:
                break
        stop.set()
        if txt is None:
            txt = "(hết thời gian chờ - thử lại hoặc /stop)"
        send_text(chat, txt)
    except Exception as e:
        stop_local = threading.Event()
        try:
            pass
        except Exception:
            pass
        send_text(chat, f"LOI: {e}")
        with open(os.path.join(HERE, "tg_bridge_err.log"), "a", encoding="utf-8") as f:
            f.write(traceback.format_exc() + "\n")

def main():
    print("[bridge] starting, owner:", state["owner"], flush=True)
    # verify server
    info = api("get", "/api/info", timeout=10)
    print("[bridge] server:", info.get("version"), flush=True)
    # clear pending updates
    r = requests.get(f"{TG}/getUpdates", params={"offset": -1, "timeout": 0}, timeout=30).json()
    res = r.get("result", [])
    if res:
        state["offset"] = res[-1]["update_id"]
        save_state()
    while True:
        try:
            r = requests.get(f"{TG}/getUpdates",
                             params={"offset": state["offset"] + 1, "timeout": 50}, timeout=70).json()
        except Exception as e:
            print("[bridge] poll err:", e, flush=True)
            time.sleep(3)
            continue
        for upd in r.get("result", []):
            state["offset"] = max(state["offset"], upd["update_id"])
            save_state()
            try:
                handle_update(upd)
            except Exception:
                with open(os.path.join(HERE, "tg_bridge_err.log"), "a", encoding="utf-8") as f:
                    f.write(traceback.format_exc() + "\n")

if __name__ == "__main__":
    main()
