"""
Copyright (C) 2022-2024 Stella Technologies (UK) Limited.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""

import glob
import os
import re
from typing import List

import click
from loguru import logger
from prettytable import PrettyTable

from stellanow_cli.code_generators import CsharpCodeGenerator
from stellanow_cli.exceptions.cli_exceptions import StellaNowCLIException
from stellanow_cli.services.code_generator.code_generator import CodeGeneratorService, pass_code_generator_service


class SkippedFile:
    def __init__(self, filename: str, reason: str):
        self.filename = filename
        self.reason = reason

    def __iter__(self):
        return iter([self.filename, self.reason])


def print_summary(skipped_files: List[SkippedFile]) -> None:
    if skipped_files:
        logger.info("\n==============================\n         SUMMARY\n==============================\n")

        table = PrettyTable(["File", "Reason for not comparing"])

        # Populate the table with data from your SkippedFile instances
        for skipped_file in skipped_files:
            table.add_row([skipped_file.filename, skipped_file.reason])

        logger.info(table)

        logger.info("\nSkipped Reason - Explanation:\n")
        logger.info("- Not Auto-Generated - It looks like the file was not generated by this CLI.")
        logger.info("- Event ID Not Found - The ID of the event is missing in the header comment.")


@click.command()
@click.option("--input_dir", "-i", default=".", help="The directory to read generated classes from.")
@pass_code_generator_service
def plan(service: CodeGeneratorService, input_dir, **kwargs):
    """Compares currently generated classes with the specifications fetched from the API and provides a summary of
    changes."""
    logger.info("Planning...")

    # We will need to map the file extensions to the appropriate code generators
    generators = {".cs": CsharpCodeGenerator()}

    # This is the unique comment that should be present in all auto-generated files
    auto_generated_comment = "This file is auto-generated by StellaNowCLI. DO NOT EDIT."

    skipped_files: List[SkippedFile] = []

    # Let's iterate over all the files in the input directory
    for filename in glob.iglob(f"{input_dir}/**", recursive=True):
        # Skip if the filename is a directory
        if os.path.isdir(filename):
            continue

        logger.info(f"==============================\nComparison for file: {filename}")
        _, ext = os.path.splitext(filename)
        generator = generators.get(ext)

        if generator:
            with open(filename, "r") as f:
                existing_code = f.read()

            # Check if the file was auto-generated
            if auto_generated_comment not in existing_code:
                logger.warning(f"Skipping {filename} because it was not auto-generated.")
                skipped_files.append(SkippedFile(filename, "Not Auto-Generated"))
                continue

            # Extract event ID from the auto-generated comment
            event_id_search = re.search(
                r"Event ID: ([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})",
                existing_code,
            )

            if event_id_search is None:
                logger.warning(f"Skipping {filename} because no Event ID was found.")
                skipped_files.append(SkippedFile(filename, "Event ID Not Found"))
                continue

            event_id = event_id_search.group(1)

            try:
                event_detail = service.get_event_details(event_id)

                diff = list(CsharpCodeGenerator.get_diff(event_detail, existing_code))
                if diff:
                    logger.info("Changes Detected:")
                    logger.info("".join(diff))
                    continue
            except StellaNowCLIException as e:
                logger.warning(e.message)
                skipped_files.append(SkippedFile(filename, e.message))
                continue

            logger.info(f"No changes detected.")

        else:
            logger.error(f"No generator found for file type {ext}. Skipping {filename}.")
            skipped_files.append(SkippedFile(filename, "Unsupported Language"))

    print_summary(skipped_files)


plan_cmd = plan
