import re
from typing import Optional, Union

from multi_swe_bench.harness.image import Config, File, Image
from multi_swe_bench.harness.instance import Instance, TestResult
from multi_swe_bench.harness.pull_request import PullRequest


class MrubyImageBase(Image):
    def __init__(self, pr: PullRequest, config: Config):
        self._pr = pr
        self._config = config

    @property
    def pr(self) -> PullRequest:
        return self._pr

    @property
    def config(self) -> Config:
        return self._config

    def dependency(self) -> Union[str, "Image"]:
        return "gcc:11"

    def image_tag(self) -> str:
        return "base"

    def workdir(self) -> str:
        return "base"

    def files(self) -> list[File]:
        return []

    def dockerfile(self) -> str:
        image_name = self.dependency()
        if isinstance(image_name, Image):
            image_name = image_name.image_full_name()

        if self.config.need_clone:
            code = f"RUN git clone https://github.com/{self.pr.org}/{self.pr.repo}.git /home/{self.pr.repo}"
        else:
            code = f"COPY {self.pr.repo} /home/{self.pr.repo}"

        return f"""FROM {image_name}

{self.global_env}

WORKDIR /home/
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
RUN apt update && apt install -y cmake ruby-full rake

{code}

{self.clear_env}

"""


class MrubyImageBaseCPP11(Image):
    def __init__(self, pr: PullRequest, config: Config):
        self._pr = pr
        self._config = config

    @property
    def pr(self) -> PullRequest:
        return self._pr

    @property
    def config(self) -> Config:
        return self._config

    def dependency(self) -> Union[str, "Image"]:
        return "gcc:11"

    def image_tag(self) -> str:
        return "base-cpp-11"

    def workdir(self) -> str:
        return "base-cpp-11"

    def files(self) -> list[File]:
        return []

    def dockerfile(self) -> str:
        image_name = self.dependency()
        if isinstance(image_name, Image):
            image_name = image_name.image_full_name()

        if self.config.need_clone:
            code = f"RUN git clone https://github.com/{self.pr.org}/{self.pr.repo}.git /home/{self.pr.repo}"
        else:
            code = f"COPY {self.pr.repo} /home/{self.pr.repo}"

        return f"""FROM {image_name}

{self.global_env}

WORKDIR /home/
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
RUN apt update && apt install -y cmake ruby-full rake bison

{code}

{self.clear_env}

"""


class MrubyImageDefault(Image):
    def __init__(self, pr: PullRequest, config: Config):
        self._pr = pr
        self._config = config

    @property
    def pr(self) -> PullRequest:
        return self._pr

    @property
    def config(self) -> Config:
        return self._config

    def dependency(self) -> Image | None:
        if self.pr.number <= 4968:
            return MrubyImageBaseCPP11(self.pr, self._config)
        return MrubyImageBase(self.pr, self._config)

    def image_tag(self) -> str:
        return f"pr-{self.pr.number}"

    def workdir(self) -> str:
        return f"pr-{self.pr.number}"

    def files(self) -> list[File]:
        if self.pr.number <= 4968:
            return [
                File(
                    ".",
                    "fix.patch",
                    f"{self.pr.fix_patch}",
                ),
                File(
                    ".",
                    "test.patch",
                    f"{self.pr.test_patch}",
                ),
                File(
                    ".",
                    "check_git_changes.sh",
                    """#!/bin/bash
set -e

if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
  echo "check_git_changes: Not inside a git repository"
  exit 1
fi

if [[ -n $(git status --porcelain) ]]; then
  echo "check_git_changes: Uncommitted changes"
  exit 1
fi

echo "check_git_changes: No uncommitted changes"
exit 0

    """.format(),
                ),
                File(
                    ".",
                    "prepare.sh",
                    """#!/bin/bash
set -e

cd /home/{pr.repo}
git reset --hard
bash /home/check_git_changes.sh
git checkout {pr.base.sha}
bash /home/check_git_changes.sh

    """.format(pr=self.pr),
                ),
                File(
                    ".",
                    "run.sh",
                    """#!/bin/bash
set -e

cd /home/{pr.repo}
rake
rake all test --trace
    """.format(pr=self.pr),
                ),
                File(
                    ".",
                    "test-run.sh",
                    """#!/bin/bash
set -e

cd /home/{pr.repo}
git apply --whitespace=nowarn /home/test.patch
rake
rake all test --trace

    """.format(pr=self.pr),
                ),
                File(
                    ".",
                    "fix-run.sh",
                    """#!/bin/bash
set -e

cd /home/{pr.repo}
git apply --whitespace=nowarn /home/test.patch /home/fix.patch
rake
rake all test --trace

    """.format(pr=self.pr),
                ),
            ]
        return [
            File(
                ".",
                "fix.patch",
                f"{self.pr.fix_patch}",
            ),
            File(
                ".",
                "test.patch",
                f"{self.pr.test_patch}",
            ),
            File(
                ".",
                "check_git_changes.sh",
                """#!/bin/bash
set -e

if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
  echo "check_git_changes: Not inside a git repository"
  exit 1
fi

if [[ -n $(git status --porcelain) ]]; then
  echo "check_git_changes: Uncommitted changes"
  exit 1
fi

echo "check_git_changes: No uncommitted changes"
exit 0

""".format(),
            ),
            File(
                ".",
                "prepare.sh",
                """#!/bin/bash
set -e

cd /home/{pr.repo}
git reset --hard
bash /home/check_git_changes.sh
git checkout {pr.base.sha}
bash /home/check_git_changes.sh


""".format(pr=self.pr),
            ),
            File(
                ".",
                "run.sh",
                """#!/bin/bash
set -e

cd /home/{pr.repo}
rake all test --trace
""".format(pr=self.pr),
            ),
            File(
                ".",
                "test-run.sh",
                """#!/bin/bash
set -e

cd /home/{pr.repo}
git apply --whitespace=nowarn /home/test.patch
rake all test --trace

""".format(pr=self.pr),
            ),
            File(
                ".",
                "fix-run.sh",
                """#!/bin/bash
set -e

cd /home/{pr.repo}
git apply --whitespace=nowarn /home/test.patch /home/fix.patch
rake all test --trace

""".format(pr=self.pr),
            ),
        ]

    def dockerfile(self) -> str:
        image = self.dependency()
        name = image.image_name()
        tag = image.image_tag()

        copy_commands = ""
        for file in self.files():
            copy_commands += f"COPY {file.name} /home/\n"

        prepare_commands = "RUN bash /home/prepare.sh"

        return f"""FROM {name}:{tag}

{self.global_env}

{copy_commands}

{prepare_commands}

{self.clear_env}

"""


@Instance.register("mruby", "mruby")
class Mruby(Instance):
    def __init__(self, pr: PullRequest, config: Config, *args, **kwargs):
        super().__init__()
        self._pr = pr
        self._config = config

    @property
    def pr(self) -> PullRequest:
        return self._pr

    def dependency(self) -> Optional[Image]:
        return MrubyImageDefault(self.pr, self._config)

    def run(self, run_cmd: str = "") -> str:
        if run_cmd:
            return run_cmd

        return "bash /home/run.sh"

    def test_patch_run(self, test_patch_run_cmd: str = "") -> str:
        if test_patch_run_cmd:
            return test_patch_run_cmd

        return "bash /home/test-run.sh"

    def fix_patch_run(self, fix_patch_run_cmd: str = "") -> str:
        if fix_patch_run_cmd:
            return fix_patch_run_cmd

        return "bash /home/fix-run.sh"

    def parse_log(self, test_log: str) -> TestResult:
        passed_tests = set()
        failed_tests = set()
        skipped_tests = set()
        if 4933 <= self.pr.number:
            re_pass_tests = [re.compile(r"^(.*?)\s*:\s*\.$")]
            re_fail_tests = [re.compile(r"^(.*?)\s*:\s*F$")]
            ok_count = len(re.findall(r"\sOK:\s", test_log))
            if ok_count == 2:
                passed_tests.add("build")
            else:
                failed_tests.add("build")
            for line in test_log.splitlines():
                line = line.strip()
                if not line:
                    continue

                for re_pass_test in re_pass_tests:
                    pass_match = re_pass_test.match(line)
                    if pass_match:
                        test = pass_match.group(1)
                        passed_tests.add(test)

                for re_fail_test in re_fail_tests:
                    fail_match = re_fail_test.match(line)
                    if fail_match:
                        test = fail_match.group(1)
                        failed_tests.add(test)
        elif 2784 <= self.pr.number < 4933:
            ko_numbers = re.findall(r"\sKO:\s*(\d+)", test_log)
            ignore_count = len(re.findall(r"Fail: regression for #1564", test_log))
            ko_numbers = list(map(int, ko_numbers))
            if ignore_count == 1:
                ko_numbers[1] -= 1
            if len(ko_numbers) == 2:
                passed_tests.add("build")
            else:
                failed_tests.add("build")
            if len(ko_numbers) == 2 and ko_numbers[0] == 0 and ko_numbers[1] == 0:
                passed_tests.add("all tests")
            else:
                failed_tests.add("all tests")
        elif self.pr.number < 2784:
            total_match = re.search(r"Total:\s*(\d+)", test_log)
            total = int(total_match.group(1)) if total_match else None
            ok_match = re.search(r"\sOK:\s*(\d+)", test_log)
            ok = int(ok_match.group(1)) if ok_match else None

            if total and ok and total == ok:
                passed_tests.add("all tests")
            else:
                failed_tests.add("all tests")

        return TestResult(
            passed_count=len(passed_tests),
            failed_count=len(failed_tests),
            skipped_count=len(skipped_tests),
            passed_tests=passed_tests,
            failed_tests=failed_tests,
            skipped_tests=skipped_tests,
        )
