import os
import subprocess
import sys
import json
import time
from datetime import datetime
import requests

def print_with_timestamp(message):
    current_time = time.time()
    seconds = int(current_time)
    milliseconds = int((current_time - seconds) * 1000)
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds))
    print(f"[{timestamp}.{milliseconds:03d}] {message}")
#

def authenticate():
    url = "https://api.oplab.com.br/v3/domain/users/authenticate"
    payload = {"email": "jrussi@gmail.com", "password": "jkiller77"}
    headers = {"Content-Type": "application/json"}
    response = requests.post(url, json=payload, headers=headers)
    if response.status_code != 200:
        raise Exception(f"Authentication failed: {response.text}")
    token = response.json().get("access-token")
    if not token:
        raise Exception("No access token found in the response")
    print_with_timestamp(f"Token retrieved: {token}")
    return token
#

def get_lista_ativos(access_token):
    """
    Retrieves stock data from the OPLAB API.

    Args:
        access_token (str): Your OPLAB API access token.

    Returns:
        dict or None: A dictionary containing the API response as JSON, or None if an error occurred.
    """

    url = "https://api.oplab.com.br/v3/market/stocks"
    headers = {
        'Access-Token': access_token
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)

        response = response.json()  # Parse the JSON response
        
        lista = []
        for r in response:
            lista.append(r['symbol'])
            
        return sorted(lista)

    except requests.exceptions.RequestException as e:
        print(f"Error during API request: {e}")
        return None
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON response: {e}")
        print(f"Raw response text: {response.text}") # Print the raw response for debugging
        return None
    #
#

def save_to_local(file_content, data, file_name):
    folder = f"oplaboptions_api/{data}"
    os.makedirs(folder, exist_ok=True)  # Garante que a pasta existe
    file_path = os.path.join(folder, f"{file_name}.json")  
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(file_content)
    print(f"File saved: {file_path}")  # Mensagem de confirmação
#

def compact_and_delete_folder(folder_path):
    if sys.platform.startswith("linux"):
        print("Compacting and deleting folder on Linux...")
        
        # Compact folder using tar with Zstandard compression
        compacted_file = f"{folder_path}.tar.zst"
        command = f"tar --use-compress-program='zstd' -cf {compacted_file} {folder_path}"
        subprocess.run(command, shell=True)
        
        # Remove the original folder
        command = f"rm -rf {folder_path}"
        subprocess.run(command, shell=True)
        
        print(f"Folder compacted to {compacted_file} and deleted.")
    else:
        print("This operation is only supported on Linux.")
    #
#

# Example usage (replace with your actual values)
if __name__ == "__main__":
    start_time = time.time()
    
    access_token = authenticate()
    lista_ativos = get_lista_ativos(access_token)

    if lista_ativos:
        print(json.dumps(lista_ativos[0:5], indent=4))  # Pretty-print the JSON response
        data = datetime.now().strftime("%Y_%m_%d__%H_%M")
        headers = {
            'Access-Token': access_token
        }
        
        url = f"https://api.oplab.com.br/v3/market/stocks?rank_by=volume&sort=asc&limit=1000&financial_volume_start=0"
        response = requests.get(url, headers=headers)
        file_content = response.text  # Parse the JSON response
        if file_content:
            save_to_local(file_content, data, 'Dados.txt')
        
        
        #for i, ativo in enumerate(lista_ativos[0:5]):
        for i, ativo in enumerate(lista_ativos):
            url = f"https://api.oplab.com.br/v3/market/quote?tickers={ativo}"
            response = requests.get(url, headers=headers)
            file_content = response.text  # Parse the JSON response
            if file_content:
                save_to_local(file_content, data, ativo + '_spot')
            print(f"Progress: {i + 1}/{len(lista_ativos)}")
        
            url = f"https://api.oplab.com.br/v3/market/options/{ativo}"
            response = requests.get(url, headers=headers)
            file_content = response.text  # Parse the JSON response
            if file_content:
                save_to_local(file_content, data, ativo)
            print(f"Progress: {i + 1}/{len(lista_ativos)}")
        
        end_time = time.time()
        print(f"Elapsed time: {end_time - start_time:.2f} seconds")
        
        if sys.platform.startswith("linux"):
            print("The operating system is Linux.")
            # Compact and delete the folder
            folder_path = f"oplaboptions_api/{data}"
            #compact_and_delete_folder(folder_path)
        else:
            print("The operating system is not Linux.")        
    else:
        print("Failed to retrieve stock data.")
        
