import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
TEST_WORKFLOW = ROOT / ".gitea" / "workflows" / "test.yml"
STANDARDS_WORKFLOW = ROOT / ".gitea" / "workflows" / "standards-check.yml"
UPDATE_THIRDPARTY_WORKFLOW = ROOT / ".gitea" / "workflows" / "update-thirdparty-skills.yml"
TEMPLATE_STANDARDS_WORKFLOW = (
    ROOT / "templates" / "ci" / "gitea" / ".gitea" / "workflows" / "standards-check.yml"
)


class GiteaWorkflowBootstrapTests(unittest.TestCase):
    def test_repo_workflows_do_not_call_repo_local_prepare_script_before_checkout(self):
        for workflow in (TEST_WORKFLOW, STANDARDS_WORKFLOW):
            text = workflow.read_text(encoding="utf-8")
            with self.subTest(workflow=workflow.name):
                self.assertNotIn("bash .gitea/ci/prepare_repo.sh", text)
                self.assertIn('git clone "$REPO_URL" "$REPO_DIR"', text)
                self.assertIn('echo "REPO_DIR=$REPO_DIR" >> "$GITHUB_ENV"', text)

    def test_workflows_use_isolated_repo_dirs_per_job(self):
        for workflow in (
            TEST_WORKFLOW,
            STANDARDS_WORKFLOW,
            UPDATE_THIRDPARTY_WORKFLOW,
            TEMPLATE_STANDARDS_WORKFLOW,
        ):
            text = workflow.read_text(encoding="utf-8")
            with self.subTest(workflow=workflow.name):
                self.assertNotIn('REPO_DIR="${WORKSPACE_DIR}/${REPO_NAME}"', text)
                self.assertNotIn('REPO_DIR="${{ env.WORKSPACE_DIR }}/$REPO_NAME"', text)
                self.assertIn('mktemp -d', text)
                self.assertTrue(
                    'mkdir -p "$WORKSPACE_DIR"' in text
                    or 'mkdir -p "${{ env.WORKSPACE_DIR }}"' in text
                )
                self.assertIn('echo "REPO_DIR=$REPO_DIR" >>', text)
                self.assertIn("if: always()", text)
                self.assertIn('rm -rf "$REPO_DIR"', text)

    def test_test_workflow_installs_tomli_for_python_template_validation(self):
        text = TEST_WORKFLOW.read_text(encoding="utf-8")
        self.assertIn("python3 -m pip install yamllint tomli", text)


if __name__ == "__main__":
    unittest.main()
