import requests
from textblob import TextBlob
import csv
from datetime import datetime
import time
from time import sleep

time.sleep(5)

api_file_path = 'C:/Users/jsgas/AppData/Roaming/MetaQuotes/Terminal/24F345EB9F291441AFE537834F9D8A19/MQL5/Files/Files/api.txt'
print(api_file_path)

def read_api_from_file():
    try:
        with open(api_file_path, 'r', encoding='utf-16') as file:
            raw_data = file.read()
            print(f"Raw data from file: {repr(raw_data)}")  # Print raw data
            api = raw_data.strip()  # Lee el contenido y elimina espacios en blanco adicionales
            api = api.replace('\ufeff', '')  # Remove BOM character if present
            print(f"API after stripping whitespace: {api}")
            time.sleep(5)
            return api
    except FileNotFoundError:
        print(f"El archivo {api_file_path} no existe.")
        time.sleep(5)
        return None




# Configuración de la API de Marketaux
api=read_api_from_file()
MARKETAUX_API_KEY = api#'mWpORHgs3GdjqNZkxZwnXmrFLYmG5jhAbVrF6HO2'

# Ejemplo de uso: leer el símbolo desde un archivo
symbol_file_path = 'C:/Users/jsgas/AppData/Roaming/MetaQuotes/Terminal/24F345EB9F291441AFE537834F9D8A19/MQL5/Files/Files/symbol.txt'



def get_forex_news(currency_pair, limit=5):
    url = f"https://api.marketaux.com/v1/news/all?symbols={currency_pair}&filter_entities=true&language=en&api_token={MARKETAUX_API_KEY}&limit={limit}&sectors=Forex"
    try:
        response = requests.get(url)
        data = response.json()
        print(f"Respuesta completa de la API: {data}")
        news = []
        current_rate = None

        for article in data.get('data', []):
            title = article.get('title', '')
            description = article.get('description', '')
            news.append((title, description))

            # Intentar obtener el tipo de cambio de varias maneras posibles
            entities = article.get('entities', [])
            for entity in entities:
                if entity.get('symbol') == currency_pair:
                    current_rate = entity.get('price')
                    if current_rate:
                        break

            if current_rate:
                break

        return news, current_rate
    except Exception as e:
        print(f"Error al obtener noticias de Forex: {str(e)}")
        return [], None

# Función para leer el símbolo desde el archivo
def read_symbol_from_file():
    try:
        with open(symbol_file_path, 'r', encoding='utf-16') as file:
            raw_data = file.read()
            print(f"Raw data from file: {repr(raw_data)}")  # Print raw data
            symbol = raw_data.strip()  # Lee el contenido y elimina espacios en blanco adicionales
            symbol = symbol.replace('\ufeff', '')  # Remove BOM character if present
            print(f"Symbol after stripping whitespace: {symbol}")
            return symbol
    except FileNotFoundError:
        print(f"El archivo {symbol_file_path} no existe.")
        return None

# Función para guardar el valor y el sentimiento en un archivo CSV
def save_to_csv(symbol, current_price, average_sentiment, file_path='analysis_results.csv'):
    today = datetime.now().strftime('%Y-%m-%d')
    
    try:
        with open(file_path, 'r') as f:
            pass
    except FileNotFoundError:
        with open(file_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['Date', 'Symbol', 'Current Price', 'Average Sentiment'])
    
    with open(file_path, 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([today, symbol, current_price, average_sentiment])

symbol = read_symbol_from_file()
print(symbol)

def save_sentiment_to_txt(average_sentiment, file_path='C:/Users/jsgas/AppData/Roaming/MetaQuotes/Terminal/24F345EB9F291441AFE537834F9D8A19/MQL5/Files/Files/'+str(symbol)+'sentiment.txt'):
    with open(file_path, 'w') as f:
        f.write(f"{average_sentiment:.2f}")



if symbol:
    news, current_rate = get_forex_news(symbol)

    if news:
        print(f"Noticias para {symbol}:")
        for i, (title, description) in enumerate(news, 1):
            print(f"{i}. {title}")
            print(f"   {description[:100]}...")  # Primeros 100 caracteres de la descripción
        
        print(f"\nTipo de cambio actual: {current_rate if current_rate else 'No disponible'}")

        # Calcular el sentimiento promedio
        sentiment_scores = [TextBlob(title + " " + description).sentiment.polarity for title, description in news]
        average_sentiment = sum(sentiment_scores) / len(sentiment_scores) if sentiment_scores else 0
        print(f"Sentimiento promedio: {average_sentiment:.2f}")

        # Guardar resultados en CSV
        #save_to_csv(symbol, current_rate, average_sentiment)

        # Guardar sentimiento promedio en un archivo de texto
        save_sentiment_to_txt(average_sentiment)
        print("Sentimiento promedio guardado en 'sentiment.txt'")
    else:
        print("No se pudieron obtener noticias de Forex.")
else:
    print("No se pudo obtener el símbolo del archivo.")

time.sleep(60)