#!/usr/bin/env python3
"""আম্মুর AI রিমাইন্ডার: Bolna দিয়ে কল, ওষুধ খাওয়া নিশ্চিত করা, Telegram-এ আপডেট। শুধু Python standard library।"""
import json, os, sys, time, urllib.request, urllib.parse
from pathlib import Path

HERE = Path(__file__).resolve().parent
def load_env():
    p = HERE / ".env"
    if p.exists():
        for line in p.read_text().splitlines():
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                k, v = line.split("=", 1); os.environ.setdefault(k.strip(), v.strip().strip('"'))
load_env()
API = "https://api.bolna.ai"
KEY = os.environ.get("BOLNA_API_KEY", ""); AGENT = os.environ.get("BOLNA_AGENT_ID", "")
PHONE = os.environ.get("MOM_PHONE", ""); MOM = os.environ.get("MOM_NAME", "আম্মু")
TG_TOKEN = os.environ.get("TG_BOT_TOKEN", ""); TG_CHAT = os.environ.get("TG_CHAT_ID", "")
MAX_TRIES = int(os.environ.get("MAX_TRIES", "3")); GAP_MIN = int(os.environ.get("GAP_MIN", "10"))
DONE = {"completed", "no-answer", "busy", "failed", "canceled", "stopped", "error", "balance-low"}

def http(method, url, body=None, headers=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read().decode() or "{}")

def bolna(method, path, body=None):
    return http(method, API + path, body, {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})

def tell(text):
    print("MSG:", text)
    if not (TG_TOKEN and TG_CHAT): return
    q = urllib.parse.urlencode({"chat_id": TG_CHAT, "text": text}).encode()
    try: urllib.request.urlopen(f"https://api.telegram.org/bot{TG_TOKEN}/sendMessage", data=q, timeout=20)
    except Exception as e: print("telegram error:", e)

def find(d, name):
    """extracted_data-র ভেতরে field খোঁজে (category-র ভেতরেও)। মান অথবা None।"""
    if isinstance(d, dict):
        for k, v in d.items():
            if k == name and isinstance(v, dict):
                return v.get("objective") or v.get("value") or v.get("subjective")
            if k == name and isinstance(v, str): return v
            r = find(v, name)
            if r: return r
    return None

def one_call():
    r = bolna("POST", "/call", {"agent_id": AGENT, "recipient_phone_number": PHONE})
    ex_id = r.get("execution_id")
    if not ex_id: raise RuntimeError(f"কল শুরু হয়নি: {r}")
    t0 = time.time(); ex = {}
    while time.time() - t0 < 15 * 60:
        time.sleep(15)
        ex = bolna("GET", f"/executions/{ex_id}")
        st = ex.get("status")
        if st in DONE and (st != "completed" or ex.get("extracted_data") is not None or time.time() - t0 > 12 * 60):
            break
    return ex

def main():
    missing = [k for k, v in {"BOLNA_API_KEY": KEY, "BOLNA_AGENT_ID": AGENT, "MOM_PHONE": PHONE}.items() if not v]
    if missing: sys.exit("Missing in .env: " + ", ".join(missing))
    for n in range(1, MAX_TRIES + 1):
        try: ex = one_call()
        except Exception as e:
            tell(f"⚠️ {MOM}-কে কল করতে সমস্যা হয়েছে: {e}"); ex = {"status": "error"}
        st = ex.get("status"); xd = ex.get("extracted_data") or {}
        status = (find(xd, "medicine_status") or "").strip().lower()
        note = find(xd, "message_for_you"); health = (find(xd, "health_concern") or "").strip().lower()
        if health.startswith("yes"):
            tell(f"🚨 {MOM} শরীর খারাপের কথা বলেছেন। এখনই নিজে একবার ফোন করুন।")
        if st == "completed" and status.startswith("taken"):
            msg = f"✅ {MOM} ওষুধ খেয়েছেন।"
            if note and len(note.strip()) > 2 and note.strip().lower() not in {"none", "na", "no"}:
                msg += f"\n💬 {MOM}-এর মেসেজ: “{note.strip()}”"
            tell(msg); return
        if n == MAX_TRIES: break
        if st != "completed": tell(f"📵 {MOM} কল ধরেননি ({st})। {GAP_MIN} মিনিট পর আবার কল করছি।")
        elif status.startswith("will"): tell(f"⏳ {MOM} এখন ওষুধ খাচ্ছেন। {GAP_MIN} মিনিট পর নিশ্চিত হতে আবার কল করছি।")
        else: tell(f"⚠️ {MOM} ওষুধ খাননি বা পরিষ্কার বোঝা যায়নি। {GAP_MIN} মিনিট পর আবার কল করছি।")
        time.sleep(GAP_MIN * 60)
    tell(f"❗ {MAX_TRIES} বার চেষ্টার পরেও নিশ্চিত হওয়া গেল না। দয়া করে {MOM}-কে নিজে একবার ফোন করুন।")

if __name__ == "__main__":
    main()
