# -*- coding: utf-8 -*-
# Debug MQTT: AWS IoT wss (STS từ client/credentials) — in lỗi thật
import json, io, sys, time, logging, ssl, traceback
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
logging.basicConfig(level=logging.DEBUG, format='%(levelname)s %(message)s')
log = logging.getLogger('mqtt-debug')

import paho.mqtt.client as mqtt
sys.path.insert(0, r'E:\ios\vinfast\vinfast-console')
from vinfast_core.api import VinFastAPI

core = VinFastAPI(email='minhhai113he@gmail.com', password='Minhgiang007?', region='VN')
core.auth.login()
core.auth.get_vehicles()
url = core.auth.get_aws_mqtt_url()
log.info('URL: %s', (url or 'FAIL')[:110])

def on_connect(client, u, f, rc, props=None):
    log.info('ON_CONNECT rc=%s flags=%s', rc, f)
def on_disconnect(client, u, rc, *a):
    log.info('ON_DISCONNECT rc=%s', rc)
def on_log(client, u, level, buf):
    log.debug('PLOG %s', buf)

c = mqtt.Client(client_id=f"Android_{core.vin}_dbg{int(time.time())%10000}", transport="websockets")
c.on_connect = on_connect
c.on_disconnect = on_disconnect
c.on_log = on_log
c.tls_set()
path = url.split(core.iot_endpoint)[1]
log.info('WS PATH: %s', path[:100])
c.ws_set_options(path=path)
try:
    r = c.connect(core.iot_endpoint, 443, 30)
    log.info('connect() -> %s', r)
    c.loop_start()
    time.sleep(8)
    log.info('is_connected: %s', c.is_connected())
    c.disconnect()
except Exception:
    traceback.print_exc()
