#!/usr/bin/env python3
import base64
import sys
from pathlib import Path

import paramiko

sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
PASS = "Moli@5404"
REMOTE = "/home/morteza/torbatyar"


def main():
    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)
    sftp = c.open_sftp()
    files = [
        ("backend/core-service/app/services/user_service.py", f"{REMOTE}/backend/core-service/app/services/user_service.py"),
        ("backend/services/identity-access/app/services/mobile_auth_service.py", f"{REMOTE}/backend/services/identity-access/app/services/mobile_auth_service.py"),
        ("backend/services/identity-access/app/services/registration_service.py", f"{REMOTE}/backend/services/identity-access/app/services/registration_service.py"),
        ("frontend/app/dashboard/page.tsx", f"{REMOTE}/frontend/app/dashboard/page.tsx"),
    ]
    for local, remote in files:
        sftp.put(str(ROOT / local), remote)
        print("uploaded", local)
    sftp.close()

    cmd = """
cd /home/morteza/torbatyar
docker compose restart core-service identity-access-service frontend
sleep 12
echo '===== before ====='
docker exec superapp_postgres psql -U superapp -d core_platform_db -c "SELECT mobile, keycloak_sub, mobile_verified FROM users;"
docker exec superapp_postgres psql -U superapp -d identity_access_db -c "SELECT mobile, keycloak_sub, core_user_id, mobile_verified FROM user_profiles;"
echo '===== link ====='
python3 <<'PY'
import subprocess
out = subprocess.check_output([
  "docker","exec","superapp_postgres","psql","-U","superapp","-d","identity_access_db","-t","-A","-F","|",
  "-c","SELECT mobile, keycloak_sub FROM user_profiles WHERE keycloak_sub IS NOT NULL AND mobile IS NOT NULL"
], text=True)
for line in out.strip().splitlines():
    if not line.strip() or "|" not in line:
        continue
    mobile, sub = line.split("|", 1)
    mobile, sub = mobile.strip(), sub.strip()
    esc_sub = sub.replace("'", "''")
    esc_mobile = mobile.replace("'", "''")
    sql = (
        "UPDATE users SET keycloak_sub = '" + esc_sub + "', mobile_verified = true "
        "WHERE mobile = '" + esc_mobile + "' AND (keycloak_sub IS NULL OR keycloak_sub = '');"
    )
    r = subprocess.run(
        ["docker","exec","superapp_postgres","psql","-U","superapp","-d","core_platform_db","-c",sql],
        capture_output=True, text=True,
    )
    print("linked", mobile, "->", sub, r.stdout.strip(), r.stderr.strip())
PY
echo '===== after ====='
docker exec superapp_postgres psql -U superapp -d core_platform_db -c "SELECT mobile, keycloak_sub, mobile_verified FROM users;"
curl -sS -m 5 http://127.0.0.1:8000/health; echo
curl -sS -m 5 http://127.0.0.1:8001/health; echo
"""
    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=300, get_pty=True)
    print((stdout.read() + stderr.read()).decode("utf-8", "replace")[-8000:])
    c.close()


if __name__ == "__main__":
    main()
