# Copyright (c) IBM Corporation
# SPDX-License-Identifier: MIT

import datetime
import pathlib

import typer
from rich.status import Status

from orchestrator.cli.models.parameters import AdoShowSummaryCommandParameters
from orchestrator.cli.models.types import (
    AdoShowSummarySupportedOutputFormats,
)
from orchestrator.cli.utils.generic.wrappers import get_sql_store
from orchestrator.cli.utils.output.prints import (
    ADO_SPINNER_QUERYING_DB,
    ERROR,
    SUCCESS,
    WARN,
    console_print,
    magenta,
)
from orchestrator.core.resources import CoreResourceKinds


def show_discovery_space_summary(parameters: AdoShowSummaryCommandParameters):
    import pandas as pd

    if parameters.query and parameters.resource_ids:
        console_print(
            f"{ERROR}You cannot specify space ids and queries/labels at the same time",
            stderr=True,
        )
        raise typer.Exit(1)

    sql_store = get_sql_store(
        project_context=parameters.ado_configuration.project_context
    )
    with Status(ADO_SPINNER_QUERYING_DB) as status:

        if parameters.query:
            spaces = sql_store.getResourceIdentifiersOfKind(
                kind=CoreResourceKinds.DISCOVERYSPACE.value,
                field_selectors=parameters.query,
            )

            if spaces.empty:
                console_print(
                    f"{ERROR}The query/labels provided did not match any space.",
                    stderr=True,
                )
                raise typer.Exit(1)

            parameters.resource_ids = list(spaces["IDENTIFIER"])

        # Load from DB
        space_resources = sql_store.getResources(identifiers=parameters.resource_ids)

        # Time-consuming imports
        status.update("Preparing to create your summary")
        from py_markdown_table.markdown_table import markdown_table

        from orchestrator.cli.models.space import SpaceSummary

        data = []
        result = ""
        if len(parameters.resource_ids) == 1:
            autogenerated_name = pathlib.Path(
                f"space_summary_{parameters.resource_ids[0]}.csv"
            )
        else:
            autogenerated_name = pathlib.Path(
                f"space_summary_{datetime.datetime.now(datetime.timezone.utc).timestamp()}.csv"
            )

        if parameters.output_format == AdoShowSummarySupportedOutputFormats.MARKDOWN:

            if parameters.include_properties:
                console_print(
                    f"{WARN}It's not possible to restrict the constitutive properties shown "
                    f"when using {AdoShowSummarySupportedOutputFormats.MARKDOWN.value} output.",
                    stderr=True,
                )

            for id, resource in space_resources.items():
                status.update(
                    f"Preparing summary for space {magenta(id)} ({len(data) + 1}/{len(space_resources)})"
                )
                data.append(
                    SpaceSummary(
                        id, parameters.ado_configuration.project_context
                    ).to_markdown_text()
                )

            result = "\n".join(data)

            if parameters.render_output:
                from rich.markdown import Markdown

                result = Markdown(result)
        else:

            for id, resource in space_resources.items():
                status.update(
                    f"Preparing summary for space {magenta(id)} ({len(data) + 1}/{len(space_resources)})"
                )
                data.append(
                    SpaceSummary(
                        id, parameters.ado_configuration.project_context
                    ).to_dataframe(
                        include_properties=parameters.include_properties,
                        columns_to_hide=parameters.columns_to_hide,
                    )
                )

            if not data:
                console_print(
                    f"{ERROR}No data was retrieved for any of the spaces: {parameters.resource_ids}",
                    stderr=True,
                )
                raise typer.Exit(1)

            df = pd.concat(data).fillna("")

            if parameters.output_format == AdoShowSummarySupportedOutputFormats.TABLE:
                result = (
                    markdown_table(df.to_dict(orient="records"))
                    .set_params(
                        row_sep="markdown",
                        padding_width=3,
                        padding_weight="centerright",
                        quote=False,
                    )
                    .get_markdown()
                )

                if parameters.render_output:
                    from rich.markdown import Markdown

                    result = Markdown(result)
            elif parameters.output_format == AdoShowSummarySupportedOutputFormats.CSV:
                df.to_csv(autogenerated_name)
                result = f"{SUCCESS} Output saved as {magenta(autogenerated_name)}"

    console_print(result)
