"""
Workflow Phases

Defines the 7-phase workflow for structured feature development.
"""

from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional


class WorkflowPhase(Enum):
    """The 7 phases of feature development workflow."""
    
    DISCOVERY = "discovery"           # Phase 1: Understand requirements
    EXPLORATION = "exploration"       # Phase 2: Analyze codebase
    QUESTIONS = "questions"           # Phase 3: Clarify ambiguities
    ARCHITECTURE = "architecture"     # Phase 4: Design approaches
    IMPLEMENTATION = "implementation" # Phase 5: Build feature
    REVIEW = "review"                 # Phase 6: Quality review
    SUMMARY = "summary"               # Phase 7: Document results

    @property
    def display_name(self) -> str:
        """Human-readable phase name."""
        names = {
            "discovery": "🔍 Discovery",
            "exploration": "📂 Codebase Exploration",
            "questions": "❓ Clarifying Questions",
            "architecture": "🏗️ Architecture Design",
            "implementation": "⚙️ Implementation",
            "review": "✅ Quality Review",
            "summary": "📋 Summary",
        }
        return names.get(self.value, self.value.title())

    @property
    def description(self) -> str:
        """Phase description."""
        descriptions = {
            "discovery": "Understanding what needs to be built",
            "exploration": "Analyzing existing code patterns and architecture",
            "questions": "Filling gaps and resolving ambiguities",
            "architecture": "Designing implementation approaches",
            "implementation": "Building the feature",
            "review": "Ensuring code quality and correctness",
            "summary": "Documenting what was accomplished",
        }
        return descriptions.get(self.value, "")

    def next_phase(self) -> Optional["WorkflowPhase"]:
        """Get the next phase in the workflow."""
        phases = list(WorkflowPhase)
        try:
            idx = phases.index(self)
            if idx < len(phases) - 1:
                return phases[idx + 1]
        except ValueError:
            pass
        return None


@dataclass
class PhaseResult:
    """Result of executing a workflow phase."""
    
    phase: WorkflowPhase
    success: bool
    output: str = ""
    data: dict[str, Any] = field(default_factory=dict)
    error: Optional[str] = None
    requires_user_input: bool = False
    user_prompt: Optional[str] = None

    @classmethod
    def success_result(cls, phase: WorkflowPhase, output: str, **data) -> "PhaseResult":
        """Create a successful phase result."""
        return cls(phase=phase, success=True, output=output, data=data)

    @classmethod
    def needs_input(cls, phase: WorkflowPhase, prompt: str, **data) -> "PhaseResult":
        """Create a result that requires user input."""
        return cls(
            phase=phase,
            success=True,
            requires_user_input=True,
            user_prompt=prompt,
            data=data,
        )

    @classmethod
    def error_result(cls, phase: WorkflowPhase, error: str) -> "PhaseResult":
        """Create an error result."""
        return cls(phase=phase, success=False, error=error)


# Phase prompts for the LLM
PHASE_PROMPTS = {
    WorkflowPhase.DISCOVERY: """## Phase 1: Discovery

**Goal**: Understand what needs to be built

**Actions**:
1. If the feature request is unclear, ask the user:
   - What problem are they solving?
   - What should the feature do?
   - Any constraints or requirements?
2. Summarize your understanding
3. Confirm with the user before proceeding

Feature request: {task}
""",

    WorkflowPhase.EXPLORATION: """## Phase 2: Codebase Exploration

**Goal**: Understand relevant existing code and patterns

**Actions**:
1. Search for similar features in the codebase
2. Map the architecture and abstractions
3. Identify key files and patterns
4. List 5-10 essential files to understand

Use the search_files and list_files tools to explore the codebase.
Present a comprehensive summary of your findings.
""",

    WorkflowPhase.QUESTIONS: """## Phase 3: Clarifying Questions

**Goal**: Fill in gaps and resolve all ambiguities

**CRITICAL**: Do not skip this phase.

**Actions**:
1. Review codebase findings and original feature request
2. Identify underspecified aspects:
   - Edge cases
   - Error handling
   - Integration points
   - Backward compatibility
   - Performance needs
3. Present all questions in a clear, organized list
4. Wait for user answers before proceeding

If there are no questions, explain why and proceed.
""",

    WorkflowPhase.ARCHITECTURE: """## Phase 4: Architecture Design

**Goal**: Design implementation approaches with trade-offs

**Actions**:
1. Design 2-3 implementation approaches:
   - **Minimal changes**: Smallest change, maximum reuse
   - **Clean architecture**: Maintainability, elegant abstractions
   - **Pragmatic balance**: Speed + quality
2. Present trade-offs for each approach
3. Make a recommendation based on the codebase and requirements
4. Ask the user which approach they prefer
""",

    WorkflowPhase.IMPLEMENTATION: """## Phase 5: Implementation

**Goal**: Build the feature

**DO NOT START WITHOUT USER APPROVAL**

**Actions**:
1. Wait for explicit user approval
2. Read all relevant files identified in previous phases
3. Implement following the chosen architecture
4. Follow codebase conventions strictly
5. Write clean, well-documented code
""",

    WorkflowPhase.REVIEW: """## Phase 6: Quality Review

**Goal**: Ensure code is simple, DRY, elegant, and functionally correct

**Actions**:
1. Review code for:
   - Bugs and logic errors
   - Code quality (DRY, simplicity, elegance)
   - Project conventions
2. Identify high-priority issues (confidence >= 80%)
3. Present findings to user
4. Ask what they want to do (fix now, fix later, proceed as-is)
""",

    WorkflowPhase.SUMMARY: """## Phase 7: Summary

**Goal**: Document what was accomplished

**Actions**:
1. Summarize:
   - What was built
   - Key decisions made
   - Files modified
   - Suggested next steps
2. Mark the task as complete
""",
}
