"""
Handler for /gsd-rlm-plan-phase command.

This module provides the plan_phase_command handler that generates
PLAN.md files for a roadmap phase using the skill registry.

Requirements: INT-04 (plan-phase command), INT-05 (orchestrator entry)
"""

from __future__ import annotations

import logging
import re
from pathlib import Path
from typing import Any

from gsd_rlm.commands.router import CommandConfig, CommandResult
from gsd_rlm.skills.discovery import SkillRegistry

logger = logging.getLogger(__name__)


def _parse_roadmap_phases(roadmap_content: str) -> list[dict[str, Any]]:
    """Parse phases from ROADMAP.md content.

    Args:
        roadmap_content: Content of ROADMAP.md file

    Returns:
        List of phase dictionaries with name, objective, and status
    """
    phases = []

    # Match phase headers like "### Phase 1: Foundation"
    phase_pattern = re.compile(
        r"###\s+Phase\s+(\d+):\s*(.+?)(?:\n|$)",
        re.IGNORECASE,
    )

    for match in phase_pattern.finditer(roadmap_content):
        phase_num = int(match.group(1))
        phase_name = match.group(2).strip()

        # Find the objective for this phase
        remaining = roadmap_content[match.end() :]
        next_phase = phase_pattern.search(remaining)
        phase_section = remaining[
            : next_phase.start() if next_phase else len(remaining)
        ]

        # Extract objective
        objective_match = re.search(
            r"\*\*Objective:\*\*\s*(.+?)(?:\n|$)", phase_section
        )
        objective = objective_match.group(1).strip() if objective_match else ""

        phases.append(
            {
                "number": phase_num,
                "name": phase_name,
                "objective": objective,
                "slug": _name_to_slug(phase_name),
            }
        )

    return phases


def _name_to_slug(name: str) -> str:
    """Convert a phase name to a URL-safe slug.

    Args:
        name: Phase name like "Foundation"

    Returns:
        Slug like "foundation"
    """
    slug = name.lower()
    slug = re.sub(r"[^a-z0-9-]+", "-", slug)
    slug = re.sub(r"-+", "-", slug)
    return slug.strip("-")


def _generate_plan_content(
    phase: dict[str, Any],
    plan_number: int,
    skill: Any,
) -> str:
    """Generate PLAN.md content for a plan.

    Args:
        phase: Phase dictionary with number, name, objective
        plan_number: Plan number within the phase
        skill: SkillDefinition for planning

    Returns:
        Generated PLAN.md content
    """
    phase_num = phase["number"]
    phase_name = phase["name"]
    phase_slug = phase["slug"]
    plan_id = f"{phase_num:02d}-{plan_number:02d}"

    content = f"""---
phase: {phase_num:02d}-{phase_slug}
plan: {plan_number:02d}
type: execute
autonomous: true
---

<objective>
Plan {plan_number} for Phase {phase_num}: {phase_name}

Objective: {phase["objective"]}
</objective>

<tasks>

<task type="auto">
  <name>task 1: Implement core functionality</name>
  <action>
  Implement the core functionality for {phase_name}.
  </action>
  <verify>
    <automated>pytest tests/ -v</automated>
  </verify>
  <done>Core functionality implemented and tested</done>
</task>

</tasks>

<verification>
- All tests pass
- Code coverage meets requirements
</verification>

<success_criteria>
1. Implementation complete
2. Tests passing
3. Documentation updated
</success_criteria>

<output>
After completion, create `.planning/phases/{phase_num:02d}-{phase_slug}/{plan_id}-SUMMARY.md`
</output>
"""
    return content


async def plan_phase_command(config: CommandConfig) -> CommandResult:
    """Generate PLAN.md files for a roadmap phase.

    Loads phase context from ROADMAP.md and generates PLAN.md files
    using the planner skill.

    Args:
        config: Command configuration with:
            - args["phase"]: Phase number (1-indexed)
            - args["plan_count"]: Number of plans to generate (default: 1)
            - project_dir: Project directory with .planning/

    Returns:
        CommandResult with success status and plan count
    """
    try:
        project_dir = config.project_dir
        planning_dir = project_dir / ".planning"
        roadmap_path = planning_dir / "ROADMAP.md"

        # Check roadmap exists
        if not roadmap_path.exists():
            return CommandResult(
                success=False,
                message="ROADMAP.md not found. Run /gsd-rlm-new-project first.",
                error="ROADMAP.md not found",
            )

        # Parse roadmap
        roadmap_content = roadmap_path.read_text(encoding="utf-8")
        phases = _parse_roadmap_phases(roadmap_content)

        if not phases:
            return CommandResult(
                success=False,
                message="No phases found in ROADMAP.md",
                error="No phases defined",
            )

        # Get phase to plan
        phase_num = config.args.get("phase", 1)
        plan_count = config.args.get("plan_count", 1)

        # Find the phase
        phase = None
        for p in phases:
            if p["number"] == phase_num:
                phase = p
                break

        if not phase:
            available = [p["number"] for p in phases]
            return CommandResult(
                success=False,
                message=f"Phase {phase_num} not found. Available phases: {available}",
                error=f"Phase {phase_num} not found",
            )

        # Create phase directory
        phase_dir_name = f"{phase['number']:02d}-{phase['slug']}"
        phase_dir = planning_dir / "phases" / phase_dir_name
        phase_dir.mkdir(parents=True, exist_ok=True)

        # Try to get planner skill from registry
        skills_registry = config.config.get("skills_registry")
        planner_skill = None
        if skills_registry:
            planner_skill = skills_registry.get("gsd-rlm-plan-phase")

        # Generate plans
        plans_created = []
        for i in range(1, plan_count + 1):
            plan_id = f"{phase['number']:02d}-{i:02d}"
            plan_path = phase_dir / f"{plan_id}-PLAN.md"

            plan_content = _generate_plan_content(phase, i, planner_skill)
            plan_path.write_text(plan_content, encoding="utf-8")
            plans_created.append(str(plan_path))

            logger.info(f"Created plan: {plan_path}")

        logger.info(f"Generated {len(plans_created)} plans for phase {phase_num}")

        return CommandResult(
            success=True,
            message=f"Generated {len(plans_created)} plan(s) for Phase {phase_num}: {phase['name']}",
            data={
                "phase_number": phase_num,
                "phase_name": phase["name"],
                "plans_created": len(plans_created),
                "plan_paths": plans_created,
            },
        )

    except Exception as e:
        logger.exception(f"Failed to generate plans: {e}")
        return CommandResult(
            success=False,
            message=f"Failed to generate plans: {e}",
            error=str(e),
        )
