# -*- coding: utf8 -*-

import requests
import json
import sys
import os
import urllib3

####################################################
### 此处更改 SQLReader 在线访问用户密码
### 默认为公用测试用户密码
### 私有用户需要到 www.kexuejisuan.com 上注册
####################################################

kxjs_user_name = 'sqlreader_test'
kxjs_password = 'sqlreader_test'


####################################

sqlfile = sys.argv[1]
sql_code = ''
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


try :
    with open(sqlfile, encoding='utf-8') as sf :
        sql_code = sf.read()
        sf.close()
except UnicodeDecodeError :
    print('被解析文件编码非UTF-8，请转换成UTF-8后解析')
    exit(1)
except Exception as e :
    print(str(e))
    exit(1)

res = requests.post(
    url = 'https://www.kexuejisuan.com/online_sql_reader/',
    headers = {'User-Agent':'SQLReader Client'},
    data = {'user':kxjs_user_name, 'pwd':kxjs_password, 'sql_file_name':os.path.basename(sqlfile), 'sql_code':sql_code},
    verify=False,
)

if 'INSERT INTO' in res.text or 'insert into' in res.text:
    with open(sqlfile+'.log', 'w+') as sf :
        sf.write(res.text)
        sf.close()

    print('解析成功:')
    print('1、血缘数据查看本地日志 : %s.log' % sqlfile)
    print('2、SQL图形化(注意登录) : https://www.kexuejisuan.com/DataBloodRelationship/')
else :
    print(res.text)
