"""Lesson 2: Setting Up Your First ONA Environment."""

from __future__ import annotations

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


class FirstEnvironmentLesson(BaseLesson):
    """Teaches GitLab OAuth, creating environments, VS Code Browser, and environment lifecycle."""

    @classmethod
    def meta(cls) -> LessonMeta:
        return LessonMeta(
            id="first-environment",
            number=2,
            title="Setting Up Your First Environment",
            description="Create and connect to your first ONA environment from a GitLab repo.",
            overview="Authenticate with GitLab via OAuth, create an environment, connect via "
            "VS Code Browser, and learn the environment lifecycle.",
        )

    def steps(self) -> list[LessonStep]:
        return [
            LessonStep(
                title="Authenticating with GitLab",
                explanation=(
                    "ONA integrates with GitLab through **OAuth**. The first time you use ONA, "
                    "you'll authenticate with GitLab through the ONA dashboard. This is a "
                    "one-time setup.\n\n"
                    "After authenticating, ONA has full access to your GitLab account — you "
                    "can clone, push, and raise merge requests directly from your ONA environment "
                    "without needing Personal Access Tokens (PATs)."
                ),
                why=(
                    "OAuth is more secure than PATs because tokens are managed by ONA and can "
                    "be revoked centrally. You don't need to manually create, store, or rotate "
                    "tokens."
                ),
            ),
            LessonStep(
                title="Navigating the ONA Dashboard",
                explanation=(
                    "The **ONA dashboard** is your control center for managing environments. "
                    "Access it at: `https://ona.example.com`\n\n"
                    "**Dashboard Layout:**\n"
                    "- **Environments** (main page) — List of all your environments\n"
                    "- **Projects** — Configure prebuilds for GitLab repositories\n"
                    "- **Settings** — User preferences and dotfiles\n"
                    "- **Account** — Billing, usage, and authentication\n\n"
                    "**Environment List:**\n"
                    "Each environment shows:\n"
                    "- **Name** — Repository name + branch\n"
                    "- **Status** — Starting, Running, Stopped, Failed\n"
                    "- **Actions** — Open, Stop, Rebuild, Delete\n"
                    "- **Created** — When it was last created/started\n\n"
                    "**Key Actions:**\n"
                    "- **New Environment** button (top right) — Create from GitLab URL\n"
                    "- **Open** button — Launch VS Code Browser for a running environment\n"
                    "- **Stop** — Pause an environment (saves state)\n"
                    "- **Rebuild** — Rebuild from latest devcontainer.json\n"
                    "- **Delete** — Permanently remove an environment"
                ),
                why=(
                    "Knowing where to find these actions prevents frustration. The dashboard is "
                    "your starting point for all ONA workflows."
                ),
            ),
            LessonStep(
                title="Creating an Environment from GitLab",
                explanation=(
                    "Now that you know the dashboard layout, let's create your first environment:\n\n"
                    "1. Click the **New Environment** button (top right)\n"
                    "2. Paste the URL of your GitLab repository "
                    "(e.g., `https://gitlab.example.com/your-user/your-repo`)\n"
                    "3. (Optional) Select a specific branch\n"
                    "4. Click **Continue**\n"
                    "5. ONA will clone the repo and build the dev container\n\n"
                    "If the repository contains a `.devcontainer/devcontainer.json`, ONA will "
                    "use it automatically. Otherwise, it will use a default Ubuntu-based image.\n\n"
                    "**Watch the build logs** to see the progress and catch any errors."
                ),
            ),
            LessonStep(
                title="Connecting via VS Code Browser",
                explanation=(
                    "Once your environment is ready, connect to it by clicking **Open** in the "
                    "ONA dashboard. This launches **VS Code in your browser** — no local "
                    "installation required.\n\n"
                    "VS Code Browser gives you the full VS Code experience: editor, terminal, "
                    "extensions, debugging, and Git integration — all running in the cloud."
                ),
                why=(
                    "VS Code Browser is the primary connection method for ONA. It works from "
                    "any device with a browser, requires zero local setup, and ensures everyone "
                    "has the same editor experience."
                ),
            ),
            LessonStep(
                title="Workspace Structure",
                explanation=(
                    "Inside your ONA environment, your project is cloned to:\n\n"
                    "```\n"
                    "/workspaces/<repo-name>/\n"
                    "```\n\n"
                    "This is your working directory. The VS Code terminal opens here by default. "
                    "All file operations happen within this directory."
                ),
                code=CodeBlock(
                    language="bash",
                    source=(
                        "# Your project is at:\n"
                        "/workspaces/my-project/\n"
                        "\n"
                        "# The terminal opens here:\n"
                        "$ pwd\n"
                        "/workspaces/my-project"
                    ),
                ),
            ),
            LessonStep(
                title="Prebuilds",
                explanation=(
                    "**Prebuilds** run your dev container setup in advance, so environments "
                    "start instantly. When you associate a project for prebuilds, ONA watches "
                    "your default branch and rebuilds the environment image whenever it changes.\n\n"
                    "To enable prebuilds, associate your GitLab project in the ONA dashboard "
                    "settings."
                ),
                why=(
                    "Without prebuilds, every new environment has to install dependencies, "
                    "build assets, and run setup commands from scratch. Prebuilds can reduce "
                    "startup time from minutes to seconds."
                ),
            ),
            LessonStep(
                title="Environment Lifecycle",
                explanation=(
                    "ONA environments have four states:\n\n"
                    "- **Start**: Launch a new or stopped environment\n"
                    "- **Stop**: Pause the environment (preserves state)\n"
                    "- **Resume**: Continue a stopped environment\n"
                    "- **Delete**: Permanently remove the environment\n\n"
                    "Stopped environments preserve your files and state but don't consume "
                    "compute resources. You can resume them from the ONA dashboard."
                ),
                deep_dive=(
                    "Best practices for environment lifecycle:\n\n"
                    "- **Stop** environments at the end of the day to save resources\n"
                    "- **Resume** is faster than creating a new environment\n"
                    "- **Delete** environments for completed feature branches\n"
                    "- Use **prebuilds** so creating new environments is fast\n"
                    "- ONA may auto-stop idle environments after a configurable timeout"
                ),
            ),
            LessonStep(
                title="When to Rebuild vs Restart",
                explanation=(
                    "Knowing **when** to use each action saves time and avoids confusion:\n\n"
                    "**Start/Resume** — For daily work\n"
                    "- What: Starts or resumes a stopped environment\n"
                    "- When: Beginning your workday, picking up where you left off\n"
                    "- Duration: Fast (seconds)\n"
                    "- Preserves: Everything (files, packages, state)\n"
                    "- Command: Click **Open** in dashboard\n\n"
                    "**Stop** — To pause work\n"
                    "- What: Pauses the container, saves state\n"
                    "- When: End of day, switching contexts\n"
                    "- Preserves: All files, installed packages, running services\n"
                    "- Command: Click **Stop** in dashboard\n\n"
                    "**Rebuild** — When configs change\n"
                    "- What: Rebuilds container from devcontainer.json\n"
                    "- When: Changed devcontainer.json, updated dotfiles, or environment is broken\n"
                    "- Duration: Slow (minutes) unless prebuild available\n"
                    "- Preserves: Only git-committed code\n"
                    "- Command: `gitpod environment devcontainer rebuild`\n\n"
                    "**Delete** — To clean up\n"
                    "- What: Permanently removes the environment\n"
                    "- When: Done with feature branch, want fresh start\n"
                    "- Preserves: Nothing (permanent deletion)\n"
                    "- Command: Click **Delete** in dashboard"
                ),
                deep_dive=(
                    "**Auto-Rebuild Triggers:**\n\n"
                    "ONA automatically rebuilds when:\n"
                    "- You push changes to `.devcontainer/devcontainer.json`\n"
                    "- Your dotfiles repository is updated (after linking)\n"
                    "- You manually trigger rebuild\n\n"
                    "**Common Mistakes:**\n"
                    "- ❌ Rebuilding when you should restart (wastes time)\n"
                    "- ❌ Restarting when you should rebuild (changes don't apply)\n"
                    "- ❌ Deleting instead of stopping (loses work)\n\n"
                    "**Quick Decision Guide:**\n"
                    "- Changed devcontainer.json? → **Rebuild**\n"
                    "- Environment feels slow or broken? → **Rebuild**\n"
                    "- Just picking up work from yesterday? → **Resume/Start**\n"
                    "- End of the workday? → **Stop**\n"
                    "- Done with this branch forever? → **Delete**"
                ),
            ),
            LessonStep(
                title="Keep the README in Your Repo",
                explanation=(
                    "This lesson scaffolds a `README.md` summary in "
                    "`./cde-onboard-practice/lesson-02-first-environment/`. "
                    "If you'd like to keep it with your project, copy it into your repo "
                    "and commit the change."
                ),
                code=CodeBlock(
                    language="bash",
                    source=(
                        "# From your repo root\n"
                        "cp cde-onboard-practice/lesson-02-first-environment/README.md ./\n"
                        "git add README.md\n"
                        "git commit -m \"Add ONA environment setup notes\"\n"
                        "git push"
                    ),
                ),
            ),
        ]

    def scaffold_files(self) -> list[ScaffoldFile]:
        return [
            ScaffoldFile(
                relative_path="README.md",
                template_name="lesson_02_readme.md",
                description="Summary checklist for setting up your first ONA environment.",
            ),
        ]
