from pathlib import Path

import yaml
from colorama import Fore

from common import (
    cd_path,
    end_collapsible_section,
    exec_command,
    exit_message,
    get_env_variable,
    move_path,
    print_message,
    start_collapsible_section,
)
from src.interface.flutter_project import FlutterProjectInterface


class FlutterLib(FlutterProjectInterface):
    def compile(self):
        sci_showcase_app_path = get_env_variable("SCI_SHOWCASE_APP_PATH")

        super().compile()
        self._config_runtime_pubignore()
        self._exec_flutter_command("pub publish --dry-run")

        section_id = start_collapsible_section("Buidando projeto showcase")

        if sci_showcase_app_path and Path(sci_showcase_app_path).is_dir():
            cd_path(sci_showcase_app_path)
            self._exec_flutter_command(self._build_app_base())
            cd_path("..")
            move_path(f"{sci_showcase_app_path}/build/app", "build/app")

        end_collapsible_section(section_id)

    def package(self):
        sci_showcase_app_path = get_env_variable("SCI_SHOWCASE_APP_PATH")

        if sci_showcase_app_path and Path(sci_showcase_app_path).is_dir():
            self._send_to_firebase("development", f"app-{self.build_kind}")

        if self._is_package_private():
            print_message(
                "Biblioteca configurada como privada, não será possível publica-la dessa forma.",
                Fore.YELLOW,
            )
            exit_message(
                "Para mais informações consulte a documentação oficial: https://dart.dev/tools/pub/pubspec#publish_to"
            )

        self._config_runtime_pubignore()

        exec_command("cp -r /root/.config/pub/ /root/.config/dart/")

        self._exec_flutter_command("pub publish --force")

    @staticmethod
    def _config_runtime_pubignore():
        exec_command("touch .pubignore")

        with open(".gitignore", "r", encoding="utf-8") as gitignore_file:
            gitignore_str = gitignore_file.read()

        with open(".pubignore", "a", encoding="utf-8") as pubignore_file:
            pubignore_file.write(f"\n{gitignore_str}\nsenior-ci/\nvenv/")

    @staticmethod
    def _is_package_private():
        """
        Regras segundo a doc

        https://dart.dev/tools/pub/pubspec#publish_to
        """

        publish_to = "https://pub.dev/"

        with open("pubspec.yaml", "r", encoding="utf-8") as stream:
            try:
                pubspec = yaml.safe_load(stream)

                publish_to = pubspec["publish_to"]
            except yaml.YAMLError as exc:
                exit_message(exc)
            except KeyError:
                pass

        return publish_to == "none"
