"""
Formatting checks - black and isort validation.

Tests:
    test_black_formatted    Code formatted with black
    test_imports_sorted     Imports sorted with isort
"""

import subprocess
from dataclasses import dataclass, field
from pathlib import Path

from .base import CheckBase


@dataclass
class FormattingChecks(CheckBase):
    """Code formatting validation with black and isort."""

    def validate_black(self) -> dict:
        """Check if code is formatted with black.

        Returns:
            dict with 'valid', 'files', and 'error' keys
        """
        result = {"valid": True, "files": [], "error": None}

        try:
            proc = subprocess.run(
                ["black", "--check", "--quiet", str(self.project_root)],
                capture_output=True,
                text=True,
            )
        except FileNotFoundError:
            result["valid"] = False
            result["error"] = (
                "black is not installed. Install with: pip install black\n"
                "Or add 'black' to your project dependencies."
            )
            return result

        if proc.returncode != 0:
            result["valid"] = False
            proc_verbose = subprocess.run(
                ["black", "--check", str(self.project_root)],
                capture_output=True,
                text=True,
            )
            result["files"] = [
                line.replace("would reformat ", "")
                for line in proc_verbose.stderr.splitlines()
                if "would reformat" in line
            ]

        return result

    def validate_isort(self) -> dict:
        """Check if imports are sorted with isort.

        Returns:
            dict with 'valid', 'files', and 'error' keys
        """
        result = {"valid": True, "files": [], "error": None}

        try:
            proc = subprocess.run(
                ["isort", "--check-only", "--quiet", str(self.project_root)],
                capture_output=True,
                text=True,
            )
        except FileNotFoundError:
            result["valid"] = False
            result["error"] = (
                "isort is not installed. Install with: pip install isort\n"
                "Or add 'isort' to your project dependencies."
            )
            return result

        if proc.returncode != 0:
            result["valid"] = False
            proc_verbose = subprocess.run(
                ["isort", "--check-only", "--diff", str(self.project_root)],
                capture_output=True,
                text=True,
            )
            for line in proc_verbose.stdout.splitlines():
                if line.startswith("--- "):
                    result["files"].append(line[4:].split("\t")[0])

        return result

    def create_test_class(self):
        """Create pytest test class for formatting checks."""
        checks = self

        class FormattingTests:
            """Formatting validation tests."""

            def test_black_formatted(self):
                """Code should be formatted with black."""
                if "test_black_formatted" in checks.skip_tests:
                    return

                result = checks.validate_black()

                if result["error"]:
                    assert False, result["error"]

                assert result["valid"], (
                    f"Files not formatted with black:\n"
                    f"  {chr(10).join(result['files'][:10])}\n"
                    f"{'  ... and more' if len(result['files']) > 10 else ''}\n\n"
                    f"Run 'black .' to format."
                )

            def test_imports_sorted(self):
                """Imports should be sorted with isort."""
                if "test_imports_sorted" in checks.skip_tests:
                    return

                result = checks.validate_isort()

                if result["error"]:
                    assert False, result["error"]

                assert result["valid"], (
                    f"Imports not sorted with isort:\n"
                    f"  {chr(10).join(result['files'][:10])}\n"
                    f"{'  ... and more' if len(result['files']) > 10 else ''}\n\n"
                    f"Run 'isort .' to sort imports."
                )

        return FormattingTests
