import pathlib
import unittest

from abstra_internals.templates import new_hook_code
from tests.fixtures import BaseTest


class TestCRUDHooks(BaseTest):
    def setUp(self) -> None:
        super().setUp()
        self.client = self.get_editor_flask_client()

    def _list_hooks(self):
        # The per-type list routes were removed (dead code); the IDE reads
        # every stage through the bulk /stages route, so assertions do too.
        stages = self.client.get("/_editor/api/stages/").get_json()
        return [stage for stage in stages if stage["type"] == "hook"]

    # The per-type create routes were removed (dead code): nothing creates
    # stages over HTTP — the canvas goes through PUT /workflows and the AI
    # through MainController.create_stage. Creation here uses the controller,
    # the same live path the AI tool exercises.
    def _create_hook(self):
        return self.controller.create_stage("hook", "New hook", "hook.py")

    def test_api_list(self):
        hooks = self._list_hooks()
        self.assertEqual(len(hooks), 0)
        self._create_hook()
        hooks = self._list_hooks()
        self.assertEqual(len(hooks), 1)

    def test_change_path(self):
        hook = self._create_hook()
        self.client.put("/_editor/api/hooks/" + hook.id, json={"path": "new_path"})
        hooks = self._list_hooks()
        self.assertEqual(len(hooks), 1)
        self.assertEqual(hooks[0]["path"], "new-path")

    def test_create_hook_with_right_template(self):
        hook = self._create_hook()
        file_content = pathlib.Path(hook.file).read_text(encoding="utf-8")
        self.assertEqual(file_content, new_hook_code)


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