import sys
import importlib
from pathlib import Path
from unittest.mock import patch, MagicMock

class TestOwnershipLogic:
    """Tests for dynamic marker insertion and ownership protection."""

    def test_creates_new_file_with_marker_from_clean_source(self, tmp_path):
        import dsai_synapsis_agent_init.main
        importlib.reload(dsai_synapsis_agent_init.main)
        from dsai_synapsis_agent_init.main import _sync_file, MANAGED_MARKER

        source_file = tmp_path / "source.md"
        source_file.write_text("Clean content", encoding="utf-8")
        dest_file = tmp_path / "dest.md"

        _sync_file(source_file, dest_file, verbose=False)
        
        content = dest_file.read_text(encoding="utf-8")
        assert MANAGED_MARKER in content

    def test_compliant_marker_insertion_for_skill_md(self, tmp_path):
        import dsai_synapsis_agent_init.main
        importlib.reload(dsai_synapsis_agent_init.main)
        from dsai_synapsis_agent_init.main import _sync_file, MANAGED_MARKER

        source_file = tmp_path / "SKILL.md"
        source_file.write_text("---\nname: test\n---\nBody", encoding="utf-8")
        dest_file = tmp_path / "SKILL.md"

        _sync_file(source_file, dest_file, verbose=False)
        
        content = dest_file.read_text(encoding="utf-8")
        assert MANAGED_MARKER in content
        assert content.index(MANAGED_MARKER) > content.index("---")

    def test_skips_update_if_marker_removed_by_user(self, tmp_path):
        import dsai_synapsis_agent_init.main
        importlib.reload(dsai_synapsis_agent_init.main)
        from dsai_synapsis_agent_init.main import _sync_file, MANAGED_MARKER

        source_file = tmp_path / "source.md"
        source_file.write_text("New Template Version", encoding="utf-8")
        dest_file = tmp_path / "source.md"
        dest_file.write_text("User Modified (No Marker)", encoding="utf-8")

        with patch("builtins.print") as mock_print:
            _sync_file(source_file, dest_file, verbose=True)
            
        assert dest_file.read_text(encoding="utf-8") == "User Modified (No Marker)"

    def test_updates_if_marker_present(self, tmp_path):
        import dsai_synapsis_agent_init.main
        importlib.reload(dsai_synapsis_agent_init.main)
        from dsai_synapsis_agent_init.main import _sync_file, MANAGED_MARKER

        source_file = tmp_path / "source.md"
        source_file.write_text("New Template Content", encoding="utf-8")
        dest_file = tmp_path / "source.md"
        dest_file.write_text(f"{MANAGED_MARKER}\nOld Content", encoding="utf-8")

        _sync_file(source_file, dest_file, verbose=False)
        
        content = dest_file.read_text(encoding="utf-8")
        assert "New Template Content" in content
        assert MANAGED_MARKER in content
