#!/usr/bin/env python3
import base64
import sys

import paramiko

sys.stdout.reconfigure(encoding="utf-8", errors="replace")
PASS = "Moli@5404"


def run(cmd):
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(
        "192.168.10.162",
        username="morteza",
        password=PASS,
        timeout=30,
        allow_agent=False,
        look_for_keys=False,
    )
    b64 = base64.b64encode(cmd.encode()).decode()
    full = f"echo {PASS!r} | sudo -S -p '' bash -c 'echo {b64} | base64 -d | bash'"
    _, stdout, stderr = c.exec_command(full, timeout=180, get_pty=True)
    print((stdout.read() + stderr.read()).decode("utf-8", "replace")[-10000:])
    c.close()


run(
    """
cd /home/morteza/torbatyar
echo '===== identity startup logs ====='
docker compose logs identity-access-service 2>&1 | head -n 80
echo '===== dbs ====='
docker exec superapp_postgres psql -U superapp -d postgres -c '\\l'
echo '===== identity tables ====='
docker exec superapp_postgres psql -U superapp -d identity_access_db -c '\\dt' || echo NO_DB
echo '===== run migrations ====='
docker compose exec -T identity-access-service python scripts/ensure_db.py
docker compose exec -T identity-access-service alembic upgrade head
echo '===== tables after ====='
docker exec superapp_postgres psql -U superapp -d identity_access_db -c '\\dt'
echo '===== test ====='
curl -sS -m 20 -X POST http://127.0.0.1:8001/api/v1/auth/mobile/start \
  -H 'Content-Type: application/json' \
  -d '{"mobile":"09155105404","context":"public"}'
echo
"""
)
