import sys
import json
import requests
from bs4 import BeautifulSoup


def hidden_value(soup, field_id):
    el = soup.find(id=field_id)
    if el and el.has_attr("value"):
        return el["value"]
    return ""


def extract_current_balance(html):
    soup = BeautifulSoup(html, "html.parser")

    table = soup.find("table", {"id": lambda value: value and value.endswith("BalancesRadGrid_ctl00")})
    if not table:
        return 0.0

    headers = [th.get_text(strip=True) for th in table.select("thead th")]

    try:
        col_idx = headers.index("Current Balance")
    except ValueError:
        return 0.0

    row = table.select_one("tbody tr")
    if not row:
        return 0.0

    cells = row.find_all("td")
    if col_idx >= len(cells):
        return 0.0

    value = cells[col_idx].get_text(strip=True).replace(",", "")
    if value == "":
        return 0.0

    return float(value)


def fetch_balance(data):
    username = data.get("username", "")
    password = data.get("password", "")
    balance_type = data.get("balance_type", "")

    if not username or not password:
        return {"success": False, "message": "بيانات تسجيل الدخول ناقصة"}

    session = requests.Session()

    login_url = "https://abili.syriatel.com.sy/Login.aspx"
    home_url = "https://abili.syriatel.com.sy/Default.aspx"

    target_url = (
        "https://abili.syriatel.com.sy/ePaymentTransfer.aspx"
        if balance_type == "epayment"
        else "https://abili.syriatel.com.sy/Transfer.aspx"
    )

    headers = {
        "User-Agent": "Mozilla/5.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    }

    login_get = session.get(login_url, headers=headers, timeout=30)
    login_get.raise_for_status()

    soup = BeautifulSoup(login_get.text, "html.parser")

    payload = {
        "RadScriptManager1_TSM": hidden_value(soup, "RadScriptManager1_TSM"),
        "__EVENTTARGET": "",
        "__EVENTARGUMENT": "",
        "__VIEWSTATE": hidden_value(soup, "__VIEWSTATE"),
        "__VIEWSTATEGENERATOR": hidden_value(soup, "__VIEWSTATEGENERATOR"),
        "__EVENTVALIDATION": hidden_value(soup, "__EVENTVALIDATION"),
        "UsernameTextBox": username,
        "PasswordTextBox": password,
        "SubmitButton": "Login",
    }

    login_post = session.post(login_url, data=payload, headers=headers, timeout=30, allow_redirects=False)

    if not (login_post.status_code == 302 and login_post.headers.get("Location", "").startswith("/Default.aspx")):
        return {"success": False, "message": "فشل تسجيل الدخول إلى سيريتل"}

    session.get(home_url, headers=headers, timeout=30)

    balance_page = session.get(target_url, headers=headers, timeout=30)
    balance_page.raise_for_status()

    balance = extract_current_balance(balance_page.text)

    return {
        "success": True,
        "balance": balance,
    }


if __name__ == "__main__":
    try:
        input_data = json.loads(sys.argv[1])
        response = fetch_balance(input_data)
        print(json.dumps(response, ensure_ascii=False))
    except Exception as exc:
        print(json.dumps({
            "success": False,
            "message": str(exc),
        }, ensure_ascii=False))