"Class to store all stock performance related functions"
import sys

import pandas as pd

sys.path.append(".")
import logging
from datetime import datetime

from services.company_profile.data_classes.company_info import CompanyInfo
from services.stock_info.openbb_stock_data import OpenBBStockData
from utils.dynamo_db import DynamoDB
from utils.url_parser import parsed_url


class StockPerformance:
    "Class to fetch the stock price over some time period"

    def get_stock_info(
        self,
        ticker: str = None,
        company_url: str = None,
        provider: str = "yfinance",
        start_date: str = None,
        duration: int = 5,
        rebase=False,
    ):
        """
        Get stock price information of a company
        ticker: str: The ticker of the stock
        company_url: str: The company url
        provider: str: The provider of the stock data (default: yfinance)
        start_date: str: The start date of the stock data (default: 5 years from today)
        duration: int: The duration of the stock data (default: 5 years)
        rebase: bool: Rebase the stock prices (default: False)
        """
        openbb_stock_finder = OpenBBStockData(provider=provider)

        if not ticker and not company_url:
            raise ValueError("Ticker or company url is required to fetch stock data")

        if not ticker and company_url:
            ticker = self.get_ticker_from_company_url(company_url=company_url)

        try:

            stock_data = openbb_stock_finder.get_stock_data(
                ticker=ticker, start_date=start_date, duration=duration
            )

        except ValueError as e:
            print(f"Error fetching stock prices: {e}")
            raise ValueError(f"Error fetching stock prices: {e}") from e

        if rebase is True:
            rebased_stock_data = self.rebase_stock_prices(stock_data)
            return rebased_stock_data

        return stock_data

    @staticmethod
    def get_ticker_from_company_url(company_url=None):
        "Get the stock ticker from the company url in our DB"
        # standardize the url
        url_parsed = parsed_url(company_url)
        company_url = url_parsed.url

        if company_url:
            db = DynamoDB()
            company_info_data = db.get_item(db.company_info_table, company_url)

            if company_info_data is not None:
                company_info = CompanyInfo(**company_info_data)
            else:
                print(f"{company_url} not found in the database.")
                logging.error(
                    "%s: %s not found in the database.",
                    datetime.now().strftime("%Y/%m/%d %H:%M:%S"),
                    company_url,
                )
                raise ValueError(f"{company_url} not found in the database.")

        if company_info.stock_ticker:
            return company_info.stock_ticker

        else:
            print(f"{company_url} doesn't have a stock ticker in the database.")
            logging.error(
                "%s: %s doesn't have a stock ticker in the database.",
                datetime.now().strftime("%Y/%m/%d %H:%M:%S"),
                company_url,
            )
            raise ValueError(
                f"{company_url} doesn't have a stock ticker in the database."
            )

    def rebase_stock_prices(self, stock_data: dict):
        "Rebase the stock prices to the first date in the stock data"
        if stock_data is None:
            print("No stock data to rebase")
            return None

        rebase_stock_price = stock_data["close_price"][0]
        rebased_stock_prices = [
            price / rebase_stock_price for price in stock_data["close_price"]
        ]
        stock_data = stock_data | {"rebased_close_price": rebased_stock_prices}

        return stock_data


if __name__ == "__main__":

    # company_urls = [
    #     "https://www.northerndynastyminerals.com",
    #     "https://www.underarmour.com",
    #     "unity.com",
    #     "https://snap.com",
    # ]

    stock_price_fetcher = StockPerformance()
    # for company_url in company_urls:
    #     try:
    #         print(
    #             stock_price_fetcher.get_stock_info(
    #                 company_url=company_url,
    #                 rebase=True,
    #                 provider="yfinance",
    #                 duration=1,
    #             )
    #         )
    #     except ValueError as er:
    #         print(f"Error fetching stock prices: {er}")

    tickers = ["BTC-USD", "SPY"]
    stock_df = pd.DataFrame()

    for ticker in tickers:
        try:
            stock_data = stock_price_fetcher.get_stock_info(
                ticker=ticker, rebase=True, provider="yfinance", duration=5
            )

            # Convert to DataFrame and set the 'date' column as the index
            stock_data_df = pd.DataFrame(stock_data).set_index("date")

            # Rename the price column to the ticker symbol
            stock_data_df = stock_data_df.add_suffix(f"_{ticker}")

            # Merge the new stock data with the existing DataFrame
            if stock_df.empty:
                stock_df = stock_data_df
            else:
                stock_df = stock_df.join(stock_data_df, how="outer")

        except ValueError as er:
            print(f"Error fetching stock prices: {er}")

    stock_df.to_excel(
        r"C:\Users\sagar\X Cap Market\X Cap Market - Customers\Formidium\excel\stock_prices.xlsx"
    )
