import re
import json
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 ImageDefault(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) -> str:
        return "python:3.11-slim"

    def image_prefix(self) -> str:
        return "envagent"

    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]:
        repo_name = self.pr.repo
        return [
            File(
                ".",
                "fix.patch",
                f"{self.pr.fix_patch}",
            ),
            File(
                ".",
                "test.patch",
                f"{self.pr.test_patch}",
            ),
            File(
                ".",
                "prepare.sh",
                """apt-get update && apt-get install -y postgresql libpq-dev
###ACTION_DELIMITER###
systemctl start postgresql && pg_isready
###ACTION_DELIMITER###
su postgres -c 'pg_ctl start -D /var/lib/postgresql/15/main' && pg_isready
###ACTION_DELIMITER###
su postgres -c '/usr/lib/postgresql/15/bin/pg_ctl start -D /var/lib/postgresql/15/main' && pg_isready
###ACTION_DELIMITER###
su postgres -c '/usr/lib/postgresql/15/bin/initdb -D /var/lib/postgresql/15/main' && su postgres -c '/usr/lib/postgresql/15/bin/pg_ctl start -D /var/lib/postgresql/15/main' && pg_isready
###ACTION_DELIMITER###
su postgres -c 'rm -rf /var/lib/postgresql/15/main && /usr/lib/postgresql/15/bin/initdb -D /var/lib/postgresql/15/main && /usr/lib/postgresql/15/bin/pg_ctl start -D /var/lib/postgresql/15/main -l /var/log/postgresql.log' && pg_isready
###ACTION_DELIMITER###
su postgres -c 'rm -rf /var/lib/postgresql/15/main && /usr/lib/postgresql/15/bin/initdb -D /var/lib/postgresql/15/main && /usr/lib/postgresql/15/bin/pg_ctl start -D /var/lib/postgresql/15/main -l /var/lib/postgresql/15/main/postgresql.log' && pg_isready
###ACTION_DELIMITER###
su postgres -c 'createdb evap && createuser -s evap' && cp evap/development/localsettings.template.py evap/localsettings.py && sed -i 's/\$SECRET_KEY/$(head -c 32 /dev/urandom | LC_ALL=C tr -dc A-Za-z0-9)/' evap/localsettings.py && sed -i "s/'HOST': os.path.join(BASE_DIR, 'data')/'HOST': 'localhost', 'PORT': '5432', 'USER': 'evap', 'PASSWORD': '', 'NAME': 'evap'/" evap/localsettings.py && uv sync && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
su postgres -c 'createdb evap && createuser -s evap' && cp evap/development/localsettings.template.py evap/localsettings.py && sed -i "s|'HOST': os.path.join(BASE_DIR, 'data')|'HOST': 'localhost', 'PORT': '5432', 'USER': 'evap', 'PASSWORD': '', 'NAME': 'evap'|" evap/localsettings.py && sed -i "s|\$SECRET_KEY|$(head -c 32 /dev/urandom | LC_ALL=C tr -dc A-Za-z0-9)|" evap/localsettings.py && uv sync && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
su postgres -c 'createuser -s evap || true && createdb -O evap evap || true' && cp -n evap/development/localsettings.template.py evap/localsettings.py && sed -i "s|'HOST': os.path.join(BASE_DIR, 'data')|'HOST': 'localhost', 'PORT': '5432', 'USER': 'evap', 'PASSWORD': '', 'NAME': 'evap'|" evap/localsettings.py && sed -i "s|\$SECRET_KEY|$(head -c 32 /dev/urandom | LC_ALL=C tr -dc A-Za-z0-9)|" evap/localsettings.py && uv sync && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
su postgres -c 'createuser -s evap || true && createdb -O evap evap || true' && cp -n evap/development/localsettings.template.py evap/localsettings.py && sed -i "s|'HOST': os.path.join(BASE_DIR, 'data')|'HOST': 'localhost', 'PORT': '5432', 'USER': 'evap', 'PASSWORD': '', 'NAME': 'evap'|" evap/localsettings.py && sed -i "s|\$SECRET_KEY|$(head -c 32 /dev/urandom | LC_ALL=C tr -dc A-Za-z0-9)|" evap/localsettings.py && pip install -r requirements.txt && ./manage.py migrate && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
pip install uv && su postgres -c 'createuser -s evap || true && createdb -O evap evap || true' && cp -n evap/development/localsettings.template.py evap/localsettings.py && sed -i "s|'HOST': os.path.join(BASE_DIR, 'data')|'HOST': 'localhost', 'PORT': '5432', 'USER': 'evap', 'PASSWORD': '', 'NAME': 'evap'|" evap/localsettings.py && sed -i "s|\$SECRET_KEY|$(head -c 32 /dev/urandom | LC_ALL=C tr -dc A-Za-z0-9)|" evap/localsettings.py && uv sync && ./manage.py migrate && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
pip install uv && su postgres -c 'createuser -s evap || true && createdb -O evap evap || true' && cp -n evap/development/localsettings.template.py evap/localsettings.py && sed -i "s|'HOST': os.path.join(BASE_DIR, 'data')|'HOST': 'localhost', 'PORT': '5432', 'USER': 'evap', 'PASSWORD': '', 'NAME': 'evap'|" evap/localsettings.py && sed -i "s|\$SECRET_KEY|$(head -c 32 /dev/urandom | LC_ALL=C tr -dc A-Za-z0-9)|" evap/localsettings.py && uv sync && source .venv/bin/activate && ./manage.py migrate && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
sed -i "s|'HOST': 'localhost'|'HOST': '/var/run/postgresql/'|" evap/localsettings.py && source .venv/bin/activate && ./manage.py migrate && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
sed -i "s|'HOST': os.path.join(BASE_DIR, 'data')|'HOST': '/var/run/postgresql/'|" evap/localsettings.py && source .venv/bin/activate && ./manage.py migrate && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
sed -i "s|'HOST': os.path.join(BASE_DIR, 'data')|'HOST': 'localhost', 'PORT': '5432'|g" evap/localsettings.py && cat evap/localsettings.py | grep 'HOST' && source .venv/bin/activate && ./manage.py migrate && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
sed -i 's|"HOST": Path("./data/").resolve()|"HOST": "/var/run/postgresql/"|g' evap/localsettings.py && cat evap/localsettings.py | grep 'HOST' && source .venv/bin/activate && ./manage.py migrate && ./manage.py test --verbosity 2
###ACTION_DELIMITER###
echo -e 'source .venv/bin/activate
./manage.py test --verbosity 2' > test_commands.sh && cat test_commands.sh""",
            ),
            File(
                ".",
                "run.sh",
                """#!/bin/bash
cd /home/[[REPO_NAME]]
source .venv/bin/activate
./manage.py test --verbosity 2

""".replace("[[REPO_NAME]]", repo_name),
            ),
            File(
                ".",
                "test-run.sh",
                """#!/bin/bash
cd /home/[[REPO_NAME]]
if ! git -C /home/[[REPO_NAME]] apply --whitespace=nowarn /home/test.patch; then
    echo "Error: git apply failed" >&2
    exit 1  
fi
source .venv/bin/activate
./manage.py test --verbosity 2

""".replace("[[REPO_NAME]]", repo_name),
            ),
            File(
                ".",
                "fix-run.sh",
                """#!/bin/bash
cd /home/[[REPO_NAME]]
if ! git -C /home/[[REPO_NAME]] apply --whitespace=nowarn  /home/test.patch /home/fix.patch; then
    echo "Error: git apply failed" >&2
    exit 1  
fi
source .venv/bin/activate
./manage.py test --verbosity 2

""".replace("[[REPO_NAME]]", repo_name),
            ),
        ]

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

        dockerfile_content = """
# This is a template for creating a Dockerfile to test patches
# LLM should fill in the appropriate values based on the context

# Choose an appropriate base image based on the project's requirements - replace [base image] with actual base image
# For example: FROM ubuntu:**, FROM python:**, FROM node:**, FROM centos:**, etc.
FROM python:3.11-slim

## Set noninteractive
ENV DEBIAN_FRONTEND=noninteractive

# Install basic requirements
# For example: RUN apt-get update && apt-get install -y git
# For example: RUN yum install -y git
# For example: RUN apk add --no-cache git
RUN apt-get update && apt-get install -y git

# Ensure bash is available
RUN if [ ! -f /bin/bash ]; then         if command -v apk >/dev/null 2>&1; then             apk add --no-cache bash;         elif command -v apt-get >/dev/null 2>&1; then             apt-get update && apt-get install -y bash;         elif command -v yum >/dev/null 2>&1; then             yum install -y bash;         else             exit 1;         fi     fi

WORKDIR /home/
COPY fix.patch /home/
COPY test.patch /home/
RUN git clone https://github.com/e-valuation/EvaP.git /home/EvaP

WORKDIR /home/EvaP
RUN git reset --hard
RUN git checkout {pr.base.sha}
"""
        dockerfile_content += f"""
{copy_commands}
"""
        return dockerfile_content.format(pr=self.pr)


@Instance.register("e-valuation", "EvaP_2434_to_2136")
class EVAP_2434_TO_2136(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 ImageDefault(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, log: str) -> TestResult:
        passed_tests = set()
        failed_tests = set()
        skipped_tests = set()
        import re

        lines = log.split("\n")
        for i, line in enumerate(lines):
            line = line.strip()
            # Handle failed tests first to avoid overlap
            if line.startswith("FAIL:"):
                fail_match = re.search(
                    r"\((evap\..+?)\)", line
                )  # Flexible test name capture
                if fail_match:
                    test_name = fail_match.group(1)
                    failed_tests.add(test_name)
                continue  # Skip to next line to avoid reprocessing
            # Extract test name for passed/skipped/failed tests
            test_match = re.search(r"\((evap\..+?)\)", line)
            if test_match:
                test_name = test_match.group(1)
                # Check current line for status
                if line.endswith("... ok"):
                    passed_tests.add(test_name)
                elif line.endswith("... skipped"):
                    skipped_tests.add(test_name)
                elif line.endswith("... FAIL"):
                    failed_tests.add(test_name)
                # Check next line if status not on current line
                elif i + 1 < len(lines):
                    next_line = lines[i + 1].strip()
                    if next_line.endswith("... ok"):
                        passed_tests.add(test_name)
                    elif next_line.endswith("... skipped"):
                        skipped_tests.add(test_name)
                    elif next_line.endswith("... FAIL"):
                        failed_tests.add(test_name)
        parsed_results = {
            "passed_tests": passed_tests,
            "failed_tests": failed_tests,
            "skipped_tests": skipped_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,
        )
