"""
Management command to generate implementation plans from completed prelim tasks.

Usage:
    # Generate plan from task
    python manage.py plan_generate <task-id>

    # Generate from prelim task
    python manage.py plan_generate <task-id> --from-prelim

    # Preview without creating
    python manage.py plan_generate <task-id> --dry-run
"""

from pathlib import Path
from typing import Any

from django.core.management.base import BaseCommand, CommandError

PLANS_DIR = Path.home() / ".claude" / "plans"


class Command(BaseCommand):
    """Generate implementation plan from completed prelim task."""

    help = "Generate implementation plan from completed prelim task"

    def add_arguments(self, parser: Any) -> None:
        parser.add_argument(
            "task_id",
            type=str,
            help="Task ID to generate plan from",
        )
        parser.add_argument(
            "--from-prelim",
            action="store_true",
            help="Use prelim task research as basis",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Preview plan without creating",
        )
        parser.add_argument(
            "--output",
            type=str,
            help="Output path for plan file (default: ~/.claude/plans/<task-id>.md)",
        )

    def handle(self, *args: Any, **options: Any) -> None:
        task_id = options["task_id"]
        from_prelim = options.get("from_prelim", False)
        dry_run = options.get("dry_run", False)
        output_path = options.get("output")

        self.stdout.write(f"\nGenerating implementation plan for task: {task_id}")
        self.stdout.write("=" * 50)

        # TODO: Fetch task from createOS API
        task = self._fetch_task(task_id)
        if not task:
            raise CommandError(f"Task not found: {task_id}")

        # Build plan content
        plan = self._build_plan(task, from_prelim)

        if dry_run:
            self.stdout.write(self.style.WARNING("\n[DRY RUN] Would create:"))
            self.stdout.write(f"\nPath: {output_path or self._get_plan_path(task_id)}")
            self.stdout.write("\nContent preview:")
            self.stdout.write("-" * 50)
            # Show first 30 lines
            for line in plan.split("\n")[:30]:
                self.stdout.write(line)
            if plan.count("\n") > 30:
                self.stdout.write("...")
            return

        # Write plan file
        plan_path = Path(output_path) if output_path else self._get_plan_path(task_id)
        plan_path.parent.mkdir(parents=True, exist_ok=True)
        plan_path.write_text(plan)

        self.stdout.write(self.style.SUCCESS(f"\n✓ Plan created: {plan_path}"))

        # TODO: Update createOS task with plan link
        self.stdout.write(self.style.WARNING("TODO: Link plan to createOS task"))

    def _fetch_task(self, task_id: str) -> dict[str, Any] | None:
        """Fetch task from createOS API."""
        # TODO: Implement createOS API call
        # For now, return placeholder
        return {
            "id": task_id,
            "title": "Placeholder task",
            "description": "TODO: Fetch from createOS",
            "story_id": None,
            "epic_id": None,
            "status": "approved",
        }

    def _get_plan_path(self, task_id: str) -> Path:
        """Get default plan file path."""
        return PLANS_DIR / f"{task_id}.md"

    def _build_plan(self, task: dict[str, Any], from_prelim: bool) -> str:
        """Build implementation plan content."""
        task_id = task["id"]
        title = task["title"]
        description = task.get("description", "")

        plan_lines = [
            f"# Implementation Plan: {title}",
            "",
            f"**Task ID:** {task_id}",
            f"**Status:** {task.get('status', 'unknown')}",
            "",
            "---",
            "",
            "## Goal",
            "",
            description or "TODO: Add goal description",
            "",
            "---",
            "",
            "## Analysis Summary",
            "",
            "| Item | Status |",
            "|------|--------|",
            "| Requirements gathered | ⏳ Pending |",
            "| Technical approach defined | ⏳ Pending |",
            "| Tests identified | ⏳ Pending |",
            "",
            "---",
            "",
            "## Implementation Approach",
            "",
            "### Phase 1: Research",
            "",
            "- [ ] Understand existing codebase",
            "- [ ] Identify affected files",
            "- [ ] Document technical approach",
            "",
            "### Phase 2: Implementation",
            "",
            "- [ ] Create/update files",
            "- [ ] Write tests",
            "- [ ] Verify functionality",
            "",
            "### Phase 3: Verification",
            "",
            "- [ ] Run tests",
            "- [ ] Code review",
            "- [ ] Deploy to staging",
            "",
            "---",
            "",
            "## Files to Create/Modify",
            "",
            "```",
            "# TODO: List files",
            "```",
            "",
            "---",
            "",
            "## Test Strategy",
            "",
            "- **Unit tests:** TODO",
            "- **Integration tests:** TODO",
            "- **E2E tests:** TODO",
            "",
            "---",
            "",
            "## Verification",
            "",
            "```bash",
            "# TODO: Add verification commands",
            "```",
            "",
        ]

        if from_prelim:
            plan_lines.extend(
                [
                    "---",
                    "",
                    "## Prelim Task Research",
                    "",
                    "TODO: Import findings from prelim task",
                    "",
                ]
            )

        return "\n".join(plan_lines)
