import requests
from dotenv import load_dotenv
import os
import logging, traceback


logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    handlers=[
        logging.FileHandler("app.log"),
        logging.StreamHandler()  # logs to console
    ]
)

script_dir = os.path.dirname(os.path.abspath(__file__))
load_dotenv(dotenv_path=f"{script_dir}/config.env", override=True)

base_url = os.getenv("API_BASE_URL")
print(f"base_url: {base_url}")

def login():
    payload = {
        "username": os.getenv("USERNAME"),
        "password": os.getenv("PASSWORD")
    }
    
    headers = {
        "Content-Type": "application/json"
    }

    response = requests.post(f"{base_url}/auth/login",json=payload,headers=headers)

    data = response.json()['data']
    jwt = data["token"]
    return jwt

def project_proccess(jwt):
    headers = {
        "Authorization": f"Bearer {jwt}",
        "Content-Type": "application/json"
    }
    response = requests.get(f"{base_url}/report/project-statistics", headers=headers)
    return response

try:
    logging.info("Script started")
    jwt = login()
    logging.info("Login Success")
    response = project_proccess(jwt)  # Call your function
    
    if response.status_code == 200:
        print("Email sent")
        logging.info("Script started")
    else:
        print(f"Failed with response: {response}")
        logging.info(f"Failed with response: {response}")
except Exception:
    msg = traceback.format_exc()
    logging.error("An error occurred:\n%s", msg)
    print(f"An error occurred: {msg }")

