# -*-coding:utf-8-*-
from api import Api
import sys
import requests
import io
import os
import json
import chardet

crop_id = sys.argv[1]
app_name = sys.argv[2]
privacy_url = sys.argv[3]
update_local = sys.argv[4]

error_url = privacy_url.replace("privacy.html","privacy_error.html")
oss_path=requests.get(error_url).text\
    .split("<Key>")[1]\
    .split("</Key>")[0]\
    .split("/")[1]

print("crop_id: %s, app_name: %s, osspath: %s"%(crop_id,app_name,oss_path))

api = Api()
success = api.new_privacy(str(crop_id), app_name, oss_path)


#是否更新本地文件
path = "../../../app/src/main/assets/web/".replace("/",os.path.sep)
if not os.path.exists(path):
    os.makedirs(path)
if success and update_local == "true":
    resp = requests.get(privacy_url);
    content = resp.text
    encode = chardet.detect(resp.content)['encoding']
    with io.open(path+"privacy.html", "w+", encoding=encode) as fout:
        fout.write(content)
        print("本地协议已更新！" + privacy_url)
    
    ksp_url=privacy_url.replace(".html","Ksp.html")
    resp = requests.get(ksp_url)
    content = resp.text
    encode = chardet.detect(resp.content)['encoding']
    if "<Code>NoSuchKey</Code>" not in content:
        with io.open(path+"privacyKsp.html", "w+", encoding=encode) as fout:
            fout.write(content)
            print("本地KSP协议已更新！" + ksp_url)
