"""
Handler for /gsd-rlm-new-project command.

This module provides the new_project_command handler that creates
the .planning/ directory structure and initializes project files.

Requirements: INT-04 (new-project command), INT-05 (orchestrator entry)
"""

from __future__ import annotations

import logging
from datetime import datetime
from pathlib import Path

from gsd_rlm.commands.router import CommandConfig, CommandResult

logger = logging.getLogger(__name__)

# Default project template
DEFAULT_PROJECT_MD = """# Project Overview

## Vision

{vision}

## Goals

{goals}

## Key Decisions

| Decision | Rationale | Date |
|----------|-----------|------|
| (Add decisions as they are made) | | |

## Technical Stack

{tech_stack}

## Success Metrics

{success_metrics}
"""

DEFAULT_ROADMAP_MD = """# Project Roadmap

## Progress

| Phase | Status | Plans |
|-------|--------|-------|
| 1. Foundation | Pending | 0/0 |
| 2. Development | Pending | 0/0 |

## Phase Overview

### Phase 1: Foundation

**Objective:** Set up core infrastructure

**Plans:**
- (Add plans as needed)

### Phase 2: Development

**Objective:** Build core features

**Plans:**
- (Add plans as needed)
"""

DEFAULT_STATE_MD = """# Project State

## Current Position

Phase: 1 of 2 (Foundation)
Plan: 0 of 0 in current phase
Status: Ready to start
Last activity: {date}

Progress: [░░░░░░░░░░] 0%

## Session Continuity

Last session: {date}
Stopped at: Project initialized
"""


async def new_project_command(config: CommandConfig) -> CommandResult:
    """Create new project structure.

    Creates the .planning/ directory with:
    - PROJECT.md - Project overview and decisions
    - ROADMAP.md - Phase and plan tracking
    - STATE.md - Current position and session info

    Args:
        config: Command configuration with:
            - args["name"]: Project name
            - args["vision"]: Optional project vision
            - project_dir: Directory to create project in

    Returns:
        CommandResult with success status and project info
    """
    try:
        project_dir = config.project_dir
        project_name = config.args.get("name", "Untitled Project")
        vision = config.args.get("vision", "Define your project vision here.")
        goals = config.args.get("goals", ["Goal 1", "Goal 2", "Goal 3"])
        tech_stack = config.args.get("tech_stack", "- Python 3.12+")
        success_metrics = config.args.get(
            "success_metrics", "- All tests pass\n- Code coverage > 80%"
        )

        # Create .planning directory
        planning_dir = project_dir / ".planning"
        planning_dir.mkdir(parents=True, exist_ok=True)

        # Create phases directory
        phases_dir = planning_dir / "phases"
        phases_dir.mkdir(exist_ok=True)

        # Create PROJECT.md
        project_md = planning_dir / "PROJECT.md"
        project_md.write_text(
            DEFAULT_PROJECT_MD.format(
                vision=vision,
                goals="\n".join(f"- {g}" for g in goals),
                tech_stack=tech_stack,
                success_metrics=success_metrics,
            ),
            encoding="utf-8",
        )

        # Create ROADMAP.md
        roadmap_md = planning_dir / "ROADMAP.md"
        roadmap_md.write_text(DEFAULT_ROADMAP_MD, encoding="utf-8")

        # Create STATE.md
        now = datetime.now().strftime("%Y-%m-%d")
        state_md = planning_dir / "STATE.md"
        state_md.write_text(DEFAULT_STATE_MD.format(date=now), encoding="utf-8")

        logger.info(f"Created project '{project_name}' at {project_dir}")

        return CommandResult(
            success=True,
            message=f"Created project '{project_name}' at {project_dir}",
            data={
                "name": project_name,
                "path": str(project_dir),
                "planning_dir": str(planning_dir),
                "files_created": [
                    str(project_md),
                    str(roadmap_md),
                    str(state_md),
                ],
            },
        )

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