import urllib.request
import json

DB_API_URL = 'http://47.97.121.32:8080/VOLERTECH/app/api/oauth/getmysql'
DB_JDBC = 'snowy_cloud_mysql_copy'

# Query: Group by station, calculate average power generation, sort descending
sql_bytes = b'SELECT `\xe6\x89\x80\xe5\xb1\x9e\xe7\xab\x99\xe7\x82\xb9`, AVG(`\xe5\x8f\x91\xe7\x94\xb5\xe9\x87\x8f(kW)`) AS `\xe5\xb9\xb3\xe5\x9d\x87\xe5\x8f\x91\xe7\x94\xb5\xe5\x8a\x9f\xe7\x8e\x87(kW)`, COUNT(*) AS `\xe6\x95\xb0\xe6\x8d\xae\xe6\x9d\xa1\xe6\x95\xb0` FROM `\xe5\x85\x89\xe4\xbc\x8f\xe8\xae\xbe\xe5\xa4\x87\xe5\xb0\x8f\xe6\x97\xb6\xe6\x95\xb0\xe6\x8d\xae` GROUP BY `\xe6\x89\x80\xe5\xb1\x9e\xe7\xab\x99\xe7\x82\xb9` ORDER BY `\xe5\xb9\xb3\xe5\x9d\x87\xe5\x8f\x91\xe7\x94\xb5\xe5\x8a\x9f\xe7\x8e\x87(kW)` DESC'
sql = sql_bytes.decode('utf-8')

print("SQL:", sql)
req = urllib.request.Request(
    DB_API_URL,
    data=json.dumps({'sql': sql, 'basejdbc': DB_JDBC}).encode('utf-8'),
    headers={'Content-Type': 'application/json'}
)
try:
    resp = urllib.request.urlopen(req, timeout=30)
    result = json.loads(resp.read().decode('utf-8'))
    print(json.dumps(result, ensure_ascii=False, indent=2))
except Exception as e:
    print(f'Error: {e}')
