#!/usr/bin/env python3
"""
Bridge between the PHP Telegram bot and the Pasargad (PasarGuard) panel.

Usage: this script reads ONE JSON object from stdin and prints ONE JSON
object to stdout. It never takes credentials as command-line arguments
(those would be visible to anyone who can run `ps aux` on the server).

Input shape:
{
    "base_url": "https://panel.example.com",
    "username": "admin",
    "password": "...",
    "action": "create_user" | "get_usage" | "remove_user",
    ... action-specific fields (see each handler below)
}

Output shape (always exactly one line of JSON):
{"ok": true, ...}
or
{"ok": false, "error": "human-readable reason"}

Requires: pip install pasarguard --break-system-packages
"""
import asyncio
import json
import sys

try:
    from pasarguard import PasarguardAPI, Tools, UserCreate, UserStatus
except ImportError:
    print(json.dumps({
        "ok": False,
        "error": "پکیج pasarguard نصب نیست. رو سرور بزن: pip install pasarguard --break-system-packages"
    }))
    sys.exit(0)

import httpx


async def create_user(api, token, req):
    username = req.get("username") or Tools.random_username(prefix="tg")
    data_limit_gb = int(req.get("data_limit_gb") or 0)
    expire_days   = int(req.get("expire_days") or 0)

    user = await api.create_user_in_all_groups(
        UserCreate(
            username=username,
            data_limit=Tools.gb(data_limit_gb) if data_limit_gb > 0 else 0,
            expire=Tools.days(expire_days) if expire_days > 0 else 0,
            status=UserStatus.ACTIVE,
            note="Created by Telegram bot",
        ),
        token=token,
    )
    return {
        "ok": True,
        "id": user.id,
        "username": user.username,
        "subscription_url": user.subscription_url,
    }


async def get_usage(api, token, req):
    user = await api.get_user(req["username"], token=token)
    return {
        "ok": True,
        "username": user.username,
        "used_traffic": user.used_traffic,
        "data_limit": user.data_limit,
        "expire": user.expire,
        "status": str(user.status),
        "subscription_url": user.subscription_url,
    }


async def remove_user(api, token, req):
    await api.remove_user(req["username"], token=token)
    return {"ok": True}


ACTIONS = {
    "create_user": create_user,
    "get_usage":   get_usage,
    "remove_user": remove_user,
}


async def main():
    try:
        req = json.loads(sys.stdin.read())
    except Exception as e:
        print(json.dumps({"ok": False, "error": f"ورودی JSON نامعتبر: {e}"}))
        return

    action = req.get("action")
    handler = ACTIONS.get(action)
    if not handler:
        print(json.dumps({"ok": False, "error": f"اکشن نامعتبر: {action}"}))
        return

    for field in ("base_url", "username", "password"):
        if not req.get(field):
            print(json.dumps({"ok": False, "error": f"فیلد {field} خالیه — اول از تنظیمات پنل تو ربات پرش کن"}))
            return

    try:
        async with PasarguardAPI(base_url=req["base_url"], timeout=20.0) as api:
            token = await api.get_token(username=req["username"], password=req["password"])
            result = await handler(api, token.access_token, req)
            print(json.dumps(result, ensure_ascii=False))
    except httpx.HTTPStatusError as exc:
        print(json.dumps({
            "ok": False,
            "error": f"پنل خطای HTTP {exc.response.status_code} داد: {exc.response.text[:300]}"
        }, ensure_ascii=False))
    except httpx.RequestError as exc:
        print(json.dumps({"ok": False, "error": f"اتصال به پنل برقرار نشد: {exc}"}, ensure_ascii=False))
    except Exception as exc:
        print(json.dumps({"ok": False, "error": f"خطای غیرمنتظره: {exc}"}, ensure_ascii=False))


if __name__ == "__main__":
    asyncio.run(main())
