import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SYNC_WORKFLOW = ROOT / ".gitea" / "workflows" / "sync-superpowers.yml"
AUTO_UPDATE_WORKFLOW = ROOT / ".gitea" / "workflows" / "update-thirdparty-superpowers.yml"
AUTO_UPDATE_SCRIPT = ROOT / ".gitea" / "ci" / "update_thirdparty_superpowers.sh"
SYNC_SCRIPT = ROOT / ".gitea" / "ci" / "sync_superpowers.sh"


class SuperpowersWorkflowTests(unittest.TestCase):
    def test_sync_workflow_uses_manual_trigger(self):
        text = SYNC_WORKFLOW.read_text(encoding="utf-8")
        self.assertIn("workflow_dispatch:", text)

    def test_sync_workflow_runs_from_latest_main(self):
        text = SYNC_WORKFLOW.read_text(encoding="utf-8")
        self.assertIn('TARGET_BRANCH: "main"', text)
        self.assertIn('git fetch origin "${{ env.TARGET_BRANCH }}"', text)
        self.assertIn(
            'git checkout -B "${{ env.TARGET_BRANCH }}" "origin/${{ env.TARGET_BRANCH }}"',
            text,
        )

    def test_auto_update_workflow_triggers_on_main_push(self):
        text = AUTO_UPDATE_WORKFLOW.read_text(encoding="utf-8")
        self.assertIn("push:", text)
        self.assertIn("- main", text)
        self.assertIn("workflow_dispatch:", text)

    def test_auto_update_workflow_runs_update_script(self):
        text = AUTO_UPDATE_WORKFLOW.read_text(encoding="utf-8")
        self.assertIn("bash .gitea/ci/update_thirdparty_superpowers.sh", text)

    def test_auto_update_script_targets_thirdparty_branch(self):
        text = AUTO_UPDATE_SCRIPT.read_text(encoding="utf-8")
        self.assertIn('TARGET_BRANCH="${TARGET_BRANCH:-thirdparty/skill}"', text)
        self.assertIn("api.github.com/repos", text)
        self.assertIn("ls-remote", text)
        self.assertIn('git checkout -B "$TARGET_BRANCH" "origin/$TARGET_BRANCH"', text)

    def test_ci_scripts_use_ci_bot_identity(self):
        sync_text = SYNC_SCRIPT.read_text(encoding="utf-8")
        update_text = AUTO_UPDATE_SCRIPT.read_text(encoding="utf-8")

        self.assertIn('COMMIT_AUTHOR_NAME="${COMMIT_AUTHOR_NAME:-ci-bot}"', sync_text)
        self.assertIn('COMMIT_AUTHOR_EMAIL="${COMMIT_AUTHOR_EMAIL:-ci-bot@local}"', sync_text)
        self.assertIn('COMMIT_AUTHOR_NAME="${COMMIT_AUTHOR_NAME:-ci-bot}"', update_text)
        self.assertIn(
            'COMMIT_AUTHOR_EMAIL="${COMMIT_AUTHOR_EMAIL:-ci-bot@local}"',
            update_text,
        )


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