"""eodhd view"""
__docformat__ = "numpy"
import logging
import os

import matplotlib.pyplot as plt

from openbb_terminal.config_terminal import theme
from openbb_terminal.config_plot import PLOT_DPI
from openbb_terminal.decorators import check_api_key, log_start_end
from openbb_terminal.helper_funcs import (
    export_data,
    lambda_long_number_format,
    print_rich_table,
    plot_autoscale,
)
from openbb_terminal.stocks.fundamental_analysis import eodhd_model

logger = logging.getLogger(__name__)


@log_start_end(log=logger)
@check_api_key(["API_EODHD_KEY"])
def display_fundamentals(
    symbol: str,
    statement: str,
    limit: int = 10,
    quarterly: bool = False,
    ratios: bool = False,
    plot: list = None,
    export: str = "",
):
    """Display tickers balance sheet; income statement; cash flow statement

    Parameters
    ----------
    symbol: str
        Stock ticker symbol
    statement:str
        Either balance or income or cashflow
    limit: int
        Number of results to show, by default 10
    quarterly: bool
        Flag to get quarterly reports, by default False
    ratios: bool
        Shows percentage change, by default False
    plot: list
        List of row labels to plot
    export: str
        Format to export data
    """
    fundamentals = eodhd_model.get_financials(symbol, statement, quarterly, ratios)
    title_str = {
        "Balance_Sheet": "Balance Sheet",
        "Income_Statement": "Income Statement",
        "Cash_Flow": "Cash Flows",
    }[statement]

    if fundamentals.empty:
        return

    if ratios or plot:
        fundamentals = fundamentals.iloc[:, :limit]

    if plot:
        rows_plot = len(plot)
        fundamentals_plot_data = fundamentals.transpose().fillna(-1)
        fundamentals_plot_data.columns = fundamentals_plot_data.columns.str.lower()
        fundamentals_plot_data = fundamentals_plot_data.replace("-", "-1")
        fundamentals_plot_data = fundamentals_plot_data.astype(float)
        if "ttm" in list(fundamentals_plot_data.index):
            fundamentals_plot_data = fundamentals_plot_data.drop(["ttm"])
        fundamentals_plot_data = fundamentals_plot_data.sort_index()

        if not ratios:
            maximum_value = fundamentals_plot_data.max().max()
            if maximum_value > 1_000_000_000_000:
                df_rounded = fundamentals_plot_data / 1_000_000_000_000
                denomination = "in Trillions"
            elif maximum_value > 1_000_000_000:
                df_rounded = fundamentals_plot_data / 1_000_000_000
                denomination = "in Billions"
            elif maximum_value > 1_000_000:
                df_rounded = fundamentals_plot_data / 1_000_000
                denomination = "in Millions"
            elif maximum_value > 1_000:
                df_rounded = fundamentals_plot_data / 1_000
                denomination = "in Thousands"
            else:
                df_rounded = fundamentals_plot_data
                denomination = ""
        else:
            df_rounded = fundamentals_plot_data
            denomination = ""

        if rows_plot == 1:
            fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
            ax.bar(df_rounded.index, df_rounded[plot[0].replace("_", " ")])
            title = (
                f"{plot[0].replace('_', ' ').capitalize()} QoQ Growth of {symbol.upper()}"
                if ratios
                else f"{plot[0].replace('_', ' ').capitalize()} of {symbol.upper()} {denomination}"
            )
            plt.title(title)
            theme.style_primary_axis(ax)
            theme.visualize_output()
        else:
            fig, axes = plt.subplots(rows_plot)
            for i in range(rows_plot):
                axes[i].bar(
                    df_rounded.index, df_rounded[plot[i].replace("_", " ")], width=0.5
                )
                axes[i].set_title(f"{plot[i].replace('_', ' ')} {denomination}")
            theme.style_primary_axis(axes[0])
            fig.autofmt_xdate()
    else:
        # Snake case to english
        fundamentals.index = fundamentals.index.to_series().apply(
            lambda x: x.replace("_", " ").title()
        )

        # Readable numbers
        fundamentals = fundamentals.applymap(lambda_long_number_format).fillna("-")
        print_rich_table(
            fundamentals.iloc[:, :limit].applymap(lambda x: "-" if x == "nan" else x),
            show_index=True,
            title=f"{symbol} {title_str}",
        )
    export_data(
        export, os.path.dirname(os.path.abspath(__file__)), statement, fundamentals
    )
