import paramiko, sys

SERVER_IP = '101.79.17.164'
LOCAL_SQL = r'C:\GUARDiA\workspace\guardia-mall\backend\_workspace\migration_zone_delivery_areas.sql'
REMOTE_SQL = '/tmp/mall_migration_zone.sql'

c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(SERVER_IP, username='root', password='1q2w3e!Q', timeout=30)

sftp = c.open_sftp()
sftp.put(LOCAL_SQL, REMOTE_SQL)
sftp.close()
print('[OK] uploaded migration SQL')

def run(cmd):
    stdin, stdout, stderr = c.exec_command(cmd)
    out = stdout.read().decode('utf-8', 'replace')
    err = stderr.read().decode('utf-8', 'replace')
    rc = stdout.channel.recv_exit_status()
    return rc, out, err

rc, out, err = run(f'sudo -u postgres psql -d mall_db -v ON_ERROR_STOP=1 -f {REMOTE_SQL}')
print('--- psql stdout ---')
print(out)
if err.strip():
    print('--- psql stderr ---')
    print(err)
print(f'[exit={rc}]')
c.close()
sys.exit(rc)
