#!/usr/bin/env python3
import os, sys, json, ssl, urllib.request, urllib.parse, subprocess
HOME = os.path.expanduser('~')
TOKEN_PATH = os.path.join(HOME, '.credentials', 'health_input_bot_telegram_token')
BASE = os.path.join(HOME, 'AI-Coach', 'health-watcher-rev002')
SCRIPTS = os.path.join(BASE, 'scripts')
PROCESS = os.path.join(SCRIPTS, 'process_text.py')

def read_token(path):
    with open(path, 'r', encoding='utf-8') as f:
        return f.read().strip()

ctx = ssl.create_default_context()

def telegram_api(token, method, params=None):
    base = f'https://api.telegram.org/bot{token}/{method}'
    data = None
    if params is not None:
        data = urllib.parse.urlencode(params).encode('utf-8')
    req = urllib.request.Request(base, data=data)
    with urllib.request.urlopen(req, context=ctx, timeout=30) as resp:
        return json.load(resp)


def main():
    import argparse
    p = argparse.ArgumentParser()
    p.add_argument('--loop', action='store_true')
    args = p.parse_args()

    try:
        token = read_token(TOKEN_PATH)
    except Exception:
        print('FAIL: missing token')
        sys.exit(2)

    offset = None
    def handle_updates(updates):
        nonlocal offset
        seen = set()
        processed = 0
        last_id = None
        for upd in updates:
            uid = upd.get('update_id')
            last_id = uid if uid is not None else last_id
            if uid in seen:
                continue
            seen.add(uid)
            msg = upd.get('message') or {}
            text = msg.get('text')
            chat = msg.get('chat') or {}
            chat_id = chat.get('id')
            if not text or not chat_id:
                continue
            p = subprocess.run([sys.executable, PROCESS, text], cwd=SCRIPTS)
            if p.returncode == 0:
                try:
                    telegram_api(token, 'sendMessage', {'chat_id': chat_id, 'text': 'נרשם ✅'})
                except Exception:
                    pass
            else:
                try:
                    telegram_api(token, 'sendMessage', {'chat_id': chat_id, 'text': 'לא הצלחתי לרשום את הדיווח'})
                except Exception:
                    pass
            processed += 1
        if last_id is not None:
            offset = int(last_id) + 1
        return processed

    if not args.loop:
        try:
            res = telegram_api(token, 'getUpdates', {'timeout':5})
        except Exception:
            print('FAIL: getUpdates error')
            sys.exit(2)
        updates = res.get('result', [])
        processed = handle_updates(updates)
        print('processed', processed)
        sys.exit(0)

    # loop mode
    try:
        while True:
            try:
                params = {'timeout':30}
                if offset:
                    params['offset'] = offset
                res = telegram_api(token, 'getUpdates', params)
                updates = res.get('result', [])
                processed = handle_updates(updates)
                # log to stdout (systemd will capture to file)
                print('cycle processed', processed)
            except KeyboardInterrupt:
                print('exiting')
                break
            except Exception as e:
                print('getUpdates error')
            finally:
                import time
                time.sleep(2)
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    main()
