"""Lesson 3: Tasks in ONA Automations."""

from __future__ import annotations

from cde_onboard.lessons.base import BaseLesson
from cde_onboard.models import CodeBlock, LessonMeta, LessonStep, ScaffoldFile


class TasksLesson(BaseLesson):
    """Teaches .ona/automations.yaml task configuration."""

    @classmethod
    def meta(cls) -> LessonMeta:
        return LessonMeta(
            id="tasks",
            number=3,
            title="Tasks",
            description="Define automated tasks in .ona/automations.yaml.",
            overview="Learn the automations.yaml structure, trigger types, task dependencies, "
            "and how to run tasks via the CLI.",
        )

    def steps(self) -> list[LessonStep]:
        return [
            LessonStep(
                title="What Are Tasks?",
                explanation=(
                    "**Tasks** are one-off commands that run during environment lifecycle events "
                    "or on-demand. They're defined in `.ona/automations.yaml` and handle things "
                    "like installing dependencies, running migrations, and building assets.\n\n"
                    "Unlike services (which run continuously), tasks execute and complete."
                ),
            ),
            LessonStep(
                title="Automations YAML Structure",
                explanation=(
                    "Tasks live under the `tasks:` key in `.ona/automations.yaml`. Each task "
                    "has a unique key, a name, and a flat `command:` field."
                ),
                code=CodeBlock(
                    language="yaml",
                    source=(
                        "tasks:\n"
                        "  install-deps:\n"
                        "    name: Install Dependencies\n"
                        "    description: Install all project dependencies\n"
                        "    command: npm install\n"
                        "    triggeredBy:\n"
                        "      - postDevcontainerStart"
                    ),
                    filename=".ona/automations.yaml",
                ),
                why=(
                    "Notice that tasks use a **flat** `command:` field (not nested under "
                    "`commands:`). This is different from services, which use nested "
                    "`commands.start` and `commands.ready`."
                ),
            ),
            LessonStep(
                title="Trigger Types",
                explanation=(
                    "Tasks can be triggered by lifecycle events:\n\n"
                    "- **postDevcontainerStart**: After the dev container starts (first time "
                    "and rebuilds)\n"
                    "- **postEnvironmentStart**: Every time the environment starts (including "
                    "resume)\n"
                    "- **prebuild**: During prebuild only (for setup that shouldn't run on start)\n"
                    "- **manual**: Only when explicitly triggered via CLI"
                ),
                code=CodeBlock(
                    language="yaml",
                    source=(
                        "tasks:\n"
                        "  seed-data:\n"
                        "    name: Seed Development Data\n"
                        "    command: python manage.py seed --env=dev\n"
                        "    triggeredBy:\n"
                        "      - manual"
                    ),
                    filename=".ona/automations.yaml",
                ),
            ),
            LessonStep(
                title="Task Dependencies",
                explanation=(
                    "Use `dependsOn` to ensure tasks or services start before this task runs. "
                    "ONA will wait for dependencies to be ready before executing the task."
                ),
                code=CodeBlock(
                    language="yaml",
                    source=(
                        "tasks:\n"
                        "  run-migrations:\n"
                        "    name: Run Database Migrations\n"
                        "    command: python manage.py migrate\n"
                        "    triggeredBy:\n"
                        "      - postDevcontainerStart\n"
                        "    dependsOn:\n"
                        "      - install-deps"
                    ),
                    filename=".ona/automations.yaml",
                ),
                why=(
                    "Dependencies are resolved by name. Here, `install-deps` refers to another "
                    "task defined in the same file. The migration task won't run until "
                    "dependencies have completed."
                ),
            ),
            LessonStep(
                title="Running Tasks via CLI",
                explanation=(
                    "You can manually start any task from the terminal:"
                ),
                code=CodeBlock(
                    language="bash",
                    source=(
                        "# Start a specific task\n"
                        "gitpod automations task start install-deps\n"
                        "\n"
                        "# Start another task\n"
                        "gitpod automations task start seed-data"
                    ),
                ),
            ),
            LessonStep(
                title="Complete Example",
                explanation=(
                    "Here's a full `automations.yaml` with multiple tasks showing dependencies "
                    "and different triggers. Click **Scaffold & Complete** to create this file."
                ),
                code=CodeBlock(
                    language="yaml",
                    source=(
                        "tasks:\n"
                        "  install-deps:\n"
                        "    name: Install Dependencies\n"
                        "    description: Install all project dependencies\n"
                        "    command: npm install\n"
                        "    triggeredBy:\n"
                        "      - postDevcontainerStart\n"
                        "\n"
                        "  run-migrations:\n"
                        "    name: Run Database Migrations\n"
                        "    command: python manage.py migrate\n"
                        "    triggeredBy:\n"
                        "      - postDevcontainerStart\n"
                        "    dependsOn:\n"
                        "      - install-deps\n"
                        "\n"
                        "  seed-data:\n"
                        "    name: Seed Development Data\n"
                        "    command: python manage.py seed --env=dev\n"
                        "    triggeredBy:\n"
                        "      - manual\n"
                        "    dependsOn:\n"
                        "      - run-migrations"
                    ),
                    filename=".ona/automations.yaml",
                ),
            ),
            LessonStep(
                title="Testing & Verification",
                explanation=(
                    "Before pushing, verify your tasks configuration:\n\n"
                    "**1. Validate YAML Syntax**"
                ),
                code=CodeBlock(
                    language="bash",
                    source=(
                        "# Check YAML syntax\n"
                        "python3 -c 'import yaml; yaml.safe_load(open(\".ona/automations.yaml\"))'\n"
                        "# No output = valid YAML"
                    ),
                ),
                deep_dive=(
                    "**2. Test Commands Locally**\n\n"
                    "Run each task command manually to verify it works:\n"
                    "```bash\n"
                    "npm install          # Should complete without errors\n"
                    "python manage.py migrate  # Should run successfully\n"
                    "```\n\n"
                    "**3. Test in ONA Environment**\n\n"
                    "After pushing and rebuilding your environment:\n"
                    "```bash\n"
                    "# Check task status\n"
                    "gitpod automations task list\n"
                    "\n"
                    "# View logs for a specific task\n"
                    "gitpod automations task logs install-deps\n"
                    "\n"
                    "# Manually trigger a task\n"
                    "gitpod automations task start seed-data\n"
                    "```\n\n"
                    "**Expected Success Indicators:**\n"
                    "- ✓ All triggered tasks complete without errors\n"
                    "- ✓ Dependencies respect order (migrations after install)\n"
                    "- ✓ Manual tasks only run when explicitly started\n"
                    "- ✓ Task logs show successful execution\n\n"
                    "**Common Issues:**\n"
                    "- YAML indentation errors → Use 2 spaces, not tabs\n"
                    "- Command fails → Test the command manually first\n"
                    "- Dependency loop → Check dependsOn references\n"
                    "- Wrong trigger → postDevcontainerStart vs postEnvironmentStart"
                ),
            ),
            LessonStep(
                title="Apply to Your Repository",
                explanation=(
                    "Scaffolding writes `.ona/automations.yaml` under "
                    "`./cde-onboard-practice/lesson-03-tasks/`. Copy it into your repo "
                    "before committing."
                ),
                code=CodeBlock(
                    language="bash",
                    source=(
                        "# From your repo root\n"
                        "cp -R cde-onboard-practice/lesson-03-tasks/.ona ./\n"
                        "git add .ona/automations.yaml\n"
                        "git commit -m \"Add task automations\"\n"
                        "git push"
                    ),
                ),
            ),
        ]

    def scaffold_files(self) -> list[ScaffoldFile]:
        return [
            ScaffoldFile(
                relative_path=".ona/automations.yaml",
                template_name="automations_task.yaml",
                description="Task automations showing install, migrate, seed, and build tasks.",
            ),
        ]
