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_compliant_marker_insertion_for_skill_md(self, tmp_path):
        """Test: SKILL.md source clean -> Target has marker AFTER frontmatter."""
        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_DEST.md"

        # Mock destination file name to be SKILL.md for the logic
        with patch.object(Path, 'name', 'SKILL.md'):
            _sync_file(source_file, dest_file, verbose=False)

        content = dest_file.read_text(encoding="utf-8")
        assert MANAGED_MARKER in content
        # Ensure it is AFTER the frontmatter
        assert content.strip().startswith("---")
        assert content.find(MANAGED_MARKER) > content.find("---", 3)

    def test_updates_if_marker_present(self, tmp_path):
        """Test: Managed file is updated if source changes and marker is present."""
        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 / "target.md"
        # Pre-existing managed file (with marker at bottom)
        dest_file.write_text(f"Old Content\n\n{MANAGED_MARKER}", 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

    def test_skips_if_marker_missing(self, tmp_path):
        """Test: Unmanaged (user-customized) file is NOT overwritten."""
        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 / "user_file.md"
        # User customized content (NO marker)
        dest_file.write_text("User Custom Content", encoding="utf-8")
        
        _sync_file(source_file, dest_file, verbose=False)

        content = dest_file.read_text(encoding="utf-8")
        assert "User Custom Content" in content
        assert "New Template Content" not in content
        assert MANAGED_MARKER not in content
