import requests
import json
import os
from dotenv import load_dotenv
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

# Load information for owencloud and telegram
load_dotenv()
to = int(datetime.now().timestamp()* 1000)
from_ = int((datetime.now() - relativedelta(months=3)).timestamp()* 1000)
print(f"to: {to}")
print(f"from: {from_}")
#Get Token for OwenCloud

def get_token():
    login = os.getenv("LOGIN")
    password = os.getenv("PASSWORD")
    if not login or not password:
        raise ValueError("Логин или пароль не заданы в .env")

    data = {'login': login, 'password': password}
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    req = requests.post("https://api.owencloud.ru/v1/auth/open/", json=data, headers=headers)
    if req.status_code == 200:
        answer = req.json()
        token = (answer["token"])
        print(token)
        return token
    else:
        print(f"Ошибка авторизации: {req.status_code}, {req.text}")
        return None
#Device parsing
def main():
    token = get_token()
    if not token:
        print("Не удалось получить токен. Завершаем работу.")
        return

    device_id = "296613"
    headers = {'Authorization': token}
    #data = json.dumps({'filter': ''})

    data = {
    'query': f'''{{
        "parameters":"[13716435,13716441,13716465,13716447,13716453,13716471,13716477,13716483,13716495,13716489,13716501]",
        "filename":"tmp.xlsx",
        "token":"{token}",
        "deviceId":296613,
        "from": {from_},
        "to": {to},
        "translations":{{
            "report":"Отчет",
            "period":"Период",
            "device":"Устройство",
            "time":"Дата/время",
            "reportname":"Таблица",
            "error":"Ошибка"
        }}
    }}'''
}

    req = requests.post(f"https://web.owencloud.ru/device/table-export", data=data, headers=headers)
    if req.status_code != 200:
        print(f"Ошибка запроса устройства: {req.status_code}, {req.text}")
        return

    #nswer = req.json()
    print("Now i save fia")
    with open('tmp.xlsx', 'wb') as ff:
        ff.write(req.content)


if __name__ == "__main__":
    main()
