"""Tests for project initialization templates."""

from pathlib import Path

import pytest

from orbit.training.templates import (
    generate_github_workflow,
    generate_makefile,
    generate_train_script,
    init_project,
)


class TestMakefile:
    def test_contains_targets(self):
        makefile = generate_makefile("test/dataset", "act")
        assert "check:" in makefile
        assert "train:" in makefile
        assert "verify:" in makefile
        assert "all:" in makefile
        assert "orbit gate" in makefile
        assert "lerobot-train" in makefile

    def test_uses_provided_params(self):
        makefile = generate_makefile("my/data", "diffusion_policy", "B")
        assert "DATASET = my/data" in makefile
        assert "POLICY = diffusion_policy" in makefile
        assert "MIN_GRADE = B" in makefile


class TestTrainScript:
    def test_contains_pipeline_steps(self):
        script = generate_train_script("test/dataset", "act")
        assert "orbit gate" in script
        assert "lerobot-train" in script
        assert "orbit verify" in script
        assert "#!/bin/bash" in script

    def test_exit_on_gate_failure(self):
        script = generate_train_script("test/dataset", "act")
        assert "exit 1" in script


class TestGitHubWorkflow:
    def test_contains_jobs(self):
        workflow = generate_github_workflow("test/dataset", "act")
        assert "quality-check:" in workflow
        assert "train:" in workflow
        assert "verify:" in workflow
        assert "orbit gate" in workflow
        assert "needs: quality-check" in workflow

    def test_uses_correct_dataset(self):
        workflow = generate_github_workflow("my/data", "diffusion_policy")
        assert "my/data" in workflow
        assert "diffusion_policy" in workflow


class TestInitProject:
    def test_creates_all_files(self, tmp_path):
        created = init_project("test/data", "act", str(tmp_path))
        assert len(created) == 3

        makefile = tmp_path / "Makefile"
        assert makefile.exists()
        assert "orbit gate" in makefile.read_text()

        train_sh = tmp_path / "train.sh"
        assert train_sh.exists()
        # Check executable permission
        import stat
        assert train_sh.stat().st_mode & stat.S_IXUSR

        workflow = tmp_path / ".github" / "workflows" / "train.yml"
        assert workflow.exists()
        assert "quality-check" in workflow.read_text()

    def test_creates_output_dir(self, tmp_path):
        out = tmp_path / "new_project"
        init_project("test/data", "act", str(out))
        assert out.exists()
