#!/usr/bin/env python3
"""Small CLI for cloud agents. Uses only Python's standard library."""
import argparse
import getpass
import json
import os
import sys
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

HOME = Path.home() / ".cloud_agents.json"
DEFAULT_URL = os.getenv("CLOUD_AGENTS_URL", "https://agent.kick.sh")
COLOR = sys.stdout.isatty()


def paint(text, code):
    return f"\033[{code}m{text}\033[0m" if COLOR else text


def title(text):
    print(paint(text, "1;36"))


def good(text):
    print(paint(text, "32"))


def quiet(text):
    print(paint(text, "2"))


def load():
    try:
        return json.loads(HOME.read_text())
    except (OSError, ValueError):
        return {}


def save(data):
    HOME.write_text(json.dumps(data) + "\n")
    HOME.chmod(0o600)


def base(args):
    return (args.url or load().get("url") or DEFAULT_URL).rstrip("/")


def call(args, path, method="GET", data=None, auth=True):
    headers = {"Accept": "application/json"}
    if data is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(data).encode()
    if auth:
        token = load().get("token", "")
        if not token:
            raise SystemExit("Run: cloud-agents login")
        headers["Authorization"] = f"Bearer {token}"
    request = Request(base(args) + path, data=data, headers=headers, method=method)
    try:
        with urlopen(request, timeout=20) as reply:
            return json.load(reply)
    except HTTPError as error:
        try:
            message = json.load(error).get("error", error.reason)
        except Exception:
            message = error.reason
        raise SystemExit(f"{error.code}: {message}")
    except URLError as error:
        raise SystemExit(f"Could not reach the site: {error.reason}")


def show_invoice(invoice):
    print(f"{invoice['status'].upper()}  {invoice['coin_amount']} {invoice['asset']}")
    print(f"Network: {invoice['network']}\nAddress: {invoice['address']}")
    print(f"Expires: {invoice['expires_at']}\nInvoice: {invoice['id']}")


def login(args):
    username = input("Username: ").strip()
    password = getpass.getpass("Password: ")
    result = call(args, "/api/login", "POST", {"username": username, "password": password}, False)
    save({"url": base(args), "token": result["token"], "expires_at": result["expires_at"]})
    good(f"Logged in as {result['user']['username']}. Login lasts one day.")


def me(args):
    result = call(args, "/api/me")
    user = result["user"]
    title(f"{user['username']} · {user['plan'].upper()}")
    print(f"You can run {result['job_limit']} active agent(s).")
    print(f"Jobs saved: {len(result['jobs'])}")


def jobs(args):
    rows = call(args, "/api/jobs")["jobs"]
    title("Your jobs")
    if not rows:
        print("No jobs yet.")
    for row in rows:
        print(f"{paint(row['state'], '32' if row['state'] == 'ACTIVE' else '33')}  {row['name']}  {row['id']}")
        quiet(row["prompt"].replace("\n", " ")[:100])


def run(args):
    result = call(args, "/api/jobs", "POST", {"name": args.name or "", "prompt": args.prompt})
    good(f"Started {result['name']}.")
    print(f"Job ID: {result['job_id']}")


def logs(args):
    after = None
    if args.follow:
        quiet("Reading logs. Press Ctrl-C to stop.")
    while True:
        path = f"/api/jobs/{args.job}/logs" + (f"?after={after}" if after else "")
        result = call(args, path)
        for entry in result["entries"]:
            stream = paint(entry["stream"].upper(), "33" if entry["stream"] == "stderr" else "36")
            print(f"{stream}  {entry['text']}")
        after = result.get("next_cursor") or after
        if not args.follow:
            return
        time.sleep(2)


def password(args):
    old = getpass.getpass("Current password: ")
    new = getpass.getpass("New password: ")
    if new != getpass.getpass("Repeat new password: "):
        raise SystemExit("Passwords did not match.")
    result = call(args, "/api/settings", "POST", {"old_password": old, "new_password": new})
    HOME.unlink(missing_ok=True)
    good(result["message"])


def upgrade(args):
    result = call(args, "/api/upgrade")
    title(f"Paid plan · ${result['paid_plan_usd']} USD")
    print(f"{result['paid_plan_days']} days · {result['paid_job_limit']} active agents")
    print("Coins: " + ", ".join(asset["symbol"] for asset in result["assets"]))
    print("Use: cloud-agents invoice BTC")


def invoices(args):
    rows = call(args, "/api/upgrade")["invoices"]
    title("Your invoices")
    if not rows:
        print("No invoices yet.")
    for row in rows:
        print(f"{row['status'].upper()}  {row['coin_amount']} {row['asset']}  {row['id']}")


def invoice(args):
    result = call(args, "/api/invoices", "POST", {"asset": args.asset})
    title("New invoice")
    show_invoice(result["invoice"])
    print("The QR on the website is address-only. Send the exact amount above on this network.")


def show_one_invoice(args):
    title("Invoice")
    show_invoice(call(args, f"/api/invoices/{args.invoice}")["invoice"])


def end_invoice(args):
    result = call(args, f"/api/invoices/{args.invoice}/close", "POST")
    good("Invoice ended. It remains in your history.")
    show_invoice(result["invoice"])


def admin(args):
    result = call(args, "/api/admin")
    title("Admin")
    caps, stats = result["caps"], result["stats"]
    print(f"Caps: {caps['accounts_per_ip']} accounts/IP · {caps['active_jobs']} free active jobs · ${caps['paid_plan_usd']} paid")
    print(f"Jobs: {stats['jobs']} total · {stats['active']} active · {stats['dead']} dead · {stats['logs']} logs")
    print("Users:")
    for user in result["users"]:
        s = user["stats"]
        print(f"  {user['id']}  {user['username']} · {user['plan']} · {s['jobs']} jobs / {s['logs']} logs")
    print("Invoices:")
    for row in result["invoices"]:
        print(f"  {row['status'].upper()}  {row['username']} · {row['coin_amount']} {row['asset']} · {row['id']}")


def caps(args):
    call(args, "/api/admin/caps", "POST", {"account_limit": args.accounts, "job_limit": args.jobs, "paid_price": args.price})
    good("Caps saved.")


def admin_logs(args):
    rows = call(args, "/api/admin/logs")["logs"]
    title("Recent logs")
    for row in rows:
        print(f"{row['username']} / {row['name']} / {row['stream']}: {row['text']}")


def mark_paid(args):
    call(args, f"/api/admin/invoices/{args.invoice}/paid", "POST")
    good("Invoice marked paid.")


def logout(args):
    try:
        call(args, "/api/logout", "POST")
    finally:
        HOME.unlink(missing_ok=True)
    good("Logged out.")


def main():
    parser = argparse.ArgumentParser(prog="cloud-agents", description="Simple cloud agents CLI")
    parser.add_argument("--url", help="site URL")
    sub = parser.add_subparsers(dest="command", required=True)
    for name, fn in (("login", login), ("logout", logout), ("me", me), ("jobs", jobs), ("upgrade", upgrade),
                     ("invoices", invoices), ("password", password), ("admin", admin), ("admin-logs", admin_logs)):
        sub.add_parser(name).set_defaults(fn=fn)
    p = sub.add_parser("run"); p.add_argument("prompt"); p.add_argument("--name"); p.set_defaults(fn=run)
    p = sub.add_parser("logs"); p.add_argument("job"); p.add_argument("--follow", action="store_true"); p.set_defaults(fn=logs)
    p = sub.add_parser("invoice"); p.add_argument("asset", help="for example: BTC"); p.set_defaults(fn=invoice)
    p = sub.add_parser("show-invoice"); p.add_argument("invoice"); p.set_defaults(fn=show_one_invoice)
    p = sub.add_parser("end-invoice"); p.add_argument("invoice"); p.set_defaults(fn=end_invoice)
    p = sub.add_parser("caps"); p.add_argument("accounts", type=int); p.add_argument("jobs", type=int); p.add_argument("price", type=int); p.set_defaults(fn=caps)
    p = sub.add_parser("mark-paid"); p.add_argument("invoice"); p.set_defaults(fn=mark_paid)
    args = parser.parse_args()
    args.fn(args)


if __name__ == "__main__":
    main()
