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)
to_formatted = (datetime.now())
from_formatted = to_formatted - relativedelta(months=3)

def send_telegram():
    token = os.getenv("TELEGRAM_TOKEN")
    channel_id = os.getenv("TELEGRAM_CHANNEL_ID")
    if not token or not channel_id:
        raise ValueError("Telegram токен или ID канала не заданы в .env")

    url = f"https://api.telegram.org/bot{token}/sendDocument"
    comment = f"С: {from_formatted}\nДо: {to_formatted}"
    with open('tmp.xlsx', 'rb') as file:
        r = requests.post(url, data={
            "chat_id": channel_id,
            "caption": comment
        }, files={
            "document": file
        })
    print(r.text)
    if r.status_code != 200:
        raise Exception(f"Ошибка отправки в Telegram: {r.text}")
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"])
        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)

    send_telegram()


if __name__ == "__main__":
    main()
