"""Initialize GSD-RLM in a project directory.

Creates .planning/ structure with default files for project management.

Requirements: GLOB-02 (CLI entry point - init command)
"""

from __future__ import annotations

from datetime import datetime
from pathlib import Path
from typing import Optional

import typer

from gsd_rlm.config.global_config import load_global_config, save_global_config


# Default file templates
PROJECT_TEMPLATE = """# Project: {name}

## Overview

{description}

## Tech Stack

- Python 3.10+
- See pyproject.toml for dependencies

## Key Decisions

| Decision | Rationale | Date |
|----------|-----------|------|
| Initial project structure | GSD-RLM initialized | {date} |

---
*Created by GSD-RLM*
"""

ROADMAP_TEMPLATE = """# Roadmap: {name}

## Overview

This roadmap tracks project phases and progress.

## Phases

- [ ] **Phase 1: Foundation** - Initial setup and core features

## Progress

| Phase | Plans Complete | Status |
|-------|----------------|--------|
| Phase 1: Foundation | 0/1 | Not started |

---
*Created by GSD-RLM*
*Last updated: {date}*
"""

STATE_TEMPLATE = """# Project State

## Project Reference

See: .planning/PROJECT.md

## Current Position

Phase: 1 of 1 (Foundation)
Plan: 0 of 1 in current phase
Status: Initialized, ready to plan

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

## Performance Metrics

**Velocity:**
- Total plans completed: 0
- Average duration: N/A

---
*Created: {date}*
"""


def init(
    path: Path = typer.Argument(
        Path("."), help="Directory to initialize (default: current directory)"
    ),
    name: Optional[str] = typer.Option(
        None, "--name", "-n", help="Project name (default: directory name)"
    ),
    force: bool = typer.Option(
        False, "--force", "-f", help="Overwrite existing .planning/ directory"
    ),
) -> None:
    """Initialize GSD-RLM in the current or specified directory.

    Creates .planning/ directory with:
    - PROJECT.md - Project overview and decisions
    - ROADMAP.md - Phase and plan tracking
    - STATE.md - Current position and metrics
    - phases/ - Directory for phase plans
    """
    target_dir = path.resolve()
    planning_dir = target_dir / ".planning"

    # Check if already exists
    if planning_dir.exists() and not force:
        typer.secho(
            f"Error: {planning_dir} already exists. Use --force to overwrite.",
            fg=typer.colors.RED,
        )
        raise typer.Exit(1)

    # Determine project name
    project_name = name or target_dir.name

    # Create directory structure
    typer.echo(f"Initializing GSD-RLM in {target_dir}...")

    planning_dir.mkdir(parents=True, exist_ok=True)
    (planning_dir / "phases").mkdir(exist_ok=True)

    # Get current date
    date_str = datetime.now().strftime("%Y-%m-%d")

    # Create default files
    project_md = planning_dir / "PROJECT.md"
    roadmap_md = planning_dir / "ROADMAP.md"
    state_md = planning_dir / "STATE.md"

    project_md.write_text(
        PROJECT_TEMPLATE.format(
            name=project_name, description="Project description", date=date_str
        ),
        encoding="utf-8",
    )
    roadmap_md.write_text(
        ROADMAP_TEMPLATE.format(name=project_name, date=date_str), encoding="utf-8"
    )
    state_md.write_text(STATE_TEMPLATE.format(date=date_str), encoding="utf-8")

    # Update global config to track projects (optional enhancement)
    config = load_global_config()
    # Could add project tracking here in future
    save_global_config(config)

    typer.secho(f"[OK] Initialized GSD-RLM in {target_dir}", fg=typer.colors.GREEN)
    typer.echo(f"\nCreated:")
    typer.echo(f"  - .planning/PROJECT.md")
    typer.echo(f"  - .planning/ROADMAP.md")
    typer.echo(f"  - .planning/STATE.md")
    typer.echo(f"  - .planning/phases/")
    typer.echo(f"\nNext steps:")
    typer.echo(f"  1. Edit .planning/PROJECT.md with your project details")
    typer.echo(f"  2. Run 'gsd-rlm install-commands' to set up OpenCode commands")
