#!/usr/bin/env python3
"""Currency verification — determine base currency of financial fields."""
import subprocess, base64, sys

HOST = "root@46.101.74.150"
KEY = "/root/ir-assessment/redteam/yajny/L3/ssh_keys/jenkins-host-id_rsa.pem"
CONTAINER = "yajny-api"

QUERIES = [
    'echo "===SALES-DISTINCT-CURRENCIES===";',
    '$sc = DB::select("SELECT currency, COUNT(*) as cnt, SUM(order_amount) as total FROM sales GROUP BY currency");',
    'foreach($sc as $r) { echo $r->currency."|".$r->cnt."|".$r->total."\n"; }',
    'echo "===USER-PAYOUTS-DISTINCT-LOCAL-CURRENCY===";',
    '$pc = DB::select("SELECT local_currency, COUNT(*) as cnt, SUM(amount) as usd_total, SUM(local_amount) as local_total FROM user_payouts GROUP BY local_currency");',
    'foreach($pc as $r) { echo $r->local_currency."|".$r->cnt."|".$r->usd_total."|".$r->local_total."\n"; }',
    'echo "===USER-PAYOUTS-SAMPLE-WITH-CURRENCY===";',
    '$ps = DB::select("SELECT id, amount, local_currency, local_amount, currency_rate, amount_egp, amount_sar, amount_aed, amount_kwd FROM user_payouts LIMIT 5");',
    'foreach($ps as $r) { echo json_encode($r)."\n"; }',
    'echo "===BALANCES-LOCAL-VS-USD===";',
    '$bl = DB::select("SELECT SUM(confirmed_balance) as usd_conf, SUM(confirmed_local_balance) as local_conf, SUM(pending_balance) as usd_pend, SUM(pending_local_balance) as local_pend FROM users")[0];',
    'echo "usd_confirmed: ".$bl->usd_conf."\n";',
    'echo "local_confirmed: ".$bl->local_conf."\n";',
    'echo "usd_pending: ".$bl->usd_pend."\n";',
    'echo "local_pending: ".$bl->local_pend."\n";',
    'echo "===DONE===";',
    'exit;',
]

def run_tinker(queries):
    code = "\n".join(queries)
    b64 = base64.b64encode(code.encode()).decode()
    cmd = [
        "ssh", "-i", KEY, "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new",
        HOST,
        f'echo {b64} | base64 -d | docker exec -i {CONTAINER} php /var/www/html/artisan tinker 2>&1'
    ]
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    return r.stdout, r.stderr, r.returncode

if __name__ == "__main__":
    out, err, rc = run_tinker(QUERIES)
    print(out)
    with open("/root/ir-assessment/redteam/yajny/L3/currency_check.txt", "w") as f:
        f.write(out)
