"""Forced Continuation service for generating non-negotiable agent instructions."""

from src.quality_orchestrator import VerificationResult


class ForcedContinuationService:
    """Generates forced continuation prompts for quality gate failures.

    This service creates non-negotiable, actionable prompts that instruct
    agents to fix quality gate failures. The prompts are designed to:
    - Be clear and directive (not suggestions)
    - Include specific failure details
    - Provide actionable remediation steps
    - Block completion until all gates pass
    """

    def generate_prompt(self, verification: VerificationResult) -> str:
        """Generate a forced continuation prompt for gate failures.

        Args:
            verification: VerificationResult containing gate failure details

        Returns:
            str: Non-negotiable prompt instructing agent to fix failures

        Raises:
            ValueError: If verification.all_passed is True (no failures to fix)
        """
        if verification.all_passed:
            raise ValueError(
                "Cannot generate continuation prompt when all gates pass. "
                "This method should only be called when verification fails."
            )

        # Collect failed gates
        failed_gates = {
            name: result
            for name, result in verification.gate_results.items()
            if not result.passed
        }

        # Build the prompt
        prompt_parts = [
            "QUALITY GATES FAILED - COMPLETION BLOCKED",
            "",
            "The following quality gates have failed and MUST be fixed before completion:",
            "",
        ]

        # Add details for each failed gate
        for gate_name, result in failed_gates.items():
            prompt_parts.append(f"❌ {gate_name.upper()} GATE FAILED")
            prompt_parts.append(f"   Message: {result.message}")

            # Add specific details if available
            if result.details:
                if "stderr" in result.details and result.details["stderr"]:
                    prompt_parts.append("   Details:")
                    # Include first few lines of stderr
                    stderr_lines = result.details["stderr"].split("\n")[:5]
                    for line in stderr_lines:
                        if line.strip():
                            prompt_parts.append(f"      {line}")

                # Add coverage-specific details
                if "coverage_percent" in result.details:
                    coverage = result.details["coverage_percent"]
                    minimum = result.details.get("minimum_coverage", 85.0)
                    gap = minimum - coverage
                    prompt_parts.append(f"   Current coverage: {coverage:.1f}%")
                    prompt_parts.append(f"   Required coverage: {minimum:.1f}%")
                    prompt_parts.append(f"   Coverage gap: {gap:.1f}%")

            prompt_parts.append("")

        # Add remediation instructions
        prompt_parts.extend(
            [
                "REQUIRED ACTIONS:",
                "",
            ]
        )

        # Add specific remediation steps based on which gates failed
        if "build" in failed_gates:
            prompt_parts.extend(
                [
                    "1. BUILD GATE - Fix all type errors:",
                    "   - Run: mypy src/",
                    "   - Fix all type errors reported",
                    "   - Ensure all type annotations are correct",
                    "",
                ]
            )

        if "lint" in failed_gates:
            prompt_parts.extend(
                [
                    "2. LINT GATE - Fix all linting issues:",
                    "   - Run: ruff check src/",
                    "   - Fix all errors and warnings",
                    "   - Ensure code follows style guidelines",
                    "",
                ]
            )

        if "test" in failed_gates:
            prompt_parts.extend(
                [
                    "3. TEST GATE - Fix all failing tests:",
                    "   - Run: pytest -v",
                    "   - Fix all test failures",
                    "   - Ensure 100% test pass rate",
                    "",
                ]
            )

        if "coverage" in failed_gates:
            coverage_result = failed_gates["coverage"]
            current = coverage_result.details.get("coverage_percent", 0.0)
            minimum = coverage_result.details.get("minimum_coverage", 85.0)

            prompt_parts.extend(
                [
                    "4. COVERAGE GATE - Increase test coverage:",
                    "   - Run: pytest --cov=src --cov-report=term-missing",
                    f"   - Current: {current:.1f}% | Required: {minimum:.1f}%",
                    "   - Add tests for uncovered code paths",
                    "   - Focus on files with low coverage",
                    "",
                ]
            )

        # Add final directive
        prompt_parts.extend(
            [
                "You MUST fix all failing gates before claiming completion.",
                "After fixing issues, run all quality gates again to verify.",
                "",
                "DO NOT claim completion until all gates pass.",
            ]
        )

        return "\n".join(prompt_parts)
