"""Integration tests for reading and writing XMind files."""

import json
import os
import tempfile
import zipfile

import pytest

from py_xmind16.workbook import Workbook
from py_xmind16.sheet import Sheet
from py_xmind16.topic import Topic


class TestReadWriteRoundTrip:
    """Tests for round-trip read/write operations."""
    
    def test_simple_round_trip(self):
        """Test simple save and load."""
        original = Workbook()
        sheet = original.create_sheet("Simple Sheet")
        root = sheet.get_root_topic()
        root.title = "Central Topic"
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            original.save(temp_path)
            loaded = Workbook.load(temp_path)
            
            assert loaded.sheet_count == 1
            assert loaded.get_sheet(0).title == "Simple Sheet"
            assert loaded.get_sheet(0).root_topic.title == "Central Topic"
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)
    
    def test_complex_structure_round_trip(self):
        """Test round-trip with complex topic structure."""
        original = Workbook()
        sheet = original.create_sheet("Complex Sheet")
        root = sheet.get_root_topic()
        root.title = "Project"
        
        # Add hierarchy
        req = root.add_subtopic("Requirements")
        req.add_subtopic("Functional")
        req.add_subtopic("Non-functional")
        
        design = root.add_subtopic("Design")
        arch = design.add_subtopic("Architecture")
        arch.add_subtopic("Frontend")
        arch.add_subtopic("Backend")
        
        impl = root.add_subtopic("Implementation")
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            original.save(temp_path)
            loaded = Workbook.load(temp_path)
            
            loaded_root = loaded.get_sheet(0).root_topic
            assert loaded_root.title == "Project"
            assert len(loaded_root.subtopics) == 3
            
            # Check Requirements branch
            req_topic = loaded_root.find_subtopic("Requirements")
            assert req_topic is not None
            assert len(req_topic.subtopics) == 2
            
            # Check Design branch
            design_topic = loaded_root.find_subtopic("Design")
            assert design_topic is not None
            arch_topic = design_topic.find_subtopic("Architecture")
            assert arch_topic is not None
            assert len(arch_topic.subtopics) == 2
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)
    
    def test_multiple_sheets_round_trip(self):
        """Test round-trip with multiple sheets."""
        original = Workbook()
        
        sheet1 = original.create_sheet("Sheet 1")
        sheet1.get_root_topic().title = "Root 1"
        
        sheet2 = original.create_sheet("Sheet 2")
        sheet2.get_root_topic().title = "Root 2"
        
        sheet3 = original.create_sheet("Sheet 3")
        root3 = sheet3.get_root_topic()
        root3.title = "Root 3"
        root3.add_subtopic("Child")
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            original.save(temp_path)
            loaded = Workbook.load(temp_path)
            
            assert loaded.sheet_count == 3
            assert loaded.get_sheet(0).title == "Sheet 1"
            assert loaded.get_sheet(1).title == "Sheet 2"
            assert loaded.get_sheet(2).title == "Sheet 3"
            
            assert loaded.get_sheet(0).root_topic.title == "Root 1"
            assert loaded.get_sheet(1).root_topic.title == "Root 2"
            assert loaded.get_sheet(2).root_topic.title == "Root 3"
            assert len(loaded.get_sheet(2).root_topic.subtopics) == 1
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)


class TestFileFormat:
    """Tests for XMind file format."""
    
    def test_xmind_is_zip_file(self):
        """Test that .xmind file is a valid ZIP archive."""
        workbook = Workbook()
        sheet = workbook.create_sheet()
        sheet.get_root_topic().title = "Test"
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            workbook.save(temp_path)
            
            # Verify it's a valid ZIP file
            assert zipfile.is_zipfile(temp_path)
            
            with zipfile.ZipFile(temp_path, 'r') as zf:
                # Check required files exist
                assert 'content.json' in zf.namelist()
                assert 'metadata.json' in zf.namelist()
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)
    
    def test_content_json_format(self):
        """Test content.json structure."""
        workbook = Workbook()
        sheet = workbook.create_sheet("Test Sheet")
        root = sheet.get_root_topic()
        root.title = "Root"
        root.add_subtopic("Child")
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            workbook.save(temp_path)
            
            with tempfile.TemporaryDirectory() as temp_dir:
                with zipfile.ZipFile(temp_path, 'r') as zf:
                    zf.extractall(temp_dir)
                
                with open(os.path.join(temp_dir, 'content.json'), 'r') as f:
                    content = json.load(f)
                
                # Content should be a list of sheets
                assert isinstance(content, list)
                assert len(content) == 1
                
                sheet_data = content[0]
                assert 'id' in sheet_data
                assert 'title' in sheet_data
                assert sheet_data['title'] == "Test Sheet"
                assert 'rootTopic' in sheet_data
                
                root_data = sheet_data['rootTopic']
                assert root_data['title'] == "Root"
                assert 'children' in root_data
                assert len(root_data['children']) == 1
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)
    
    def test_metadata_json_format(self):
        """Test metadata.json structure."""
        workbook = Workbook()
        workbook.create_sheet()
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            workbook.save(temp_path)
            
            with tempfile.TemporaryDirectory() as temp_dir:
                with zipfile.ZipFile(temp_path, 'r') as zf:
                    zf.extractall(temp_dir)
                
                with open(os.path.join(temp_dir, 'metadata.json'), 'r') as f:
                    metadata = json.load(f)
                
                assert 'creator' in metadata
                assert 'name' in metadata['creator']
                assert 'dataStructureVersion' in metadata
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)


class TestTopicAttributesPersistence:
    """Tests for topic attributes persistence."""
    
    def test_notes_persistence(self):
        """Test that notes are saved and loaded correctly."""
        original = Workbook()
        sheet = original.create_sheet()
        root = sheet.get_root_topic()
        root.title = "Root"
        root.notes = "These are detailed notes"
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            original.save(temp_path)
            loaded = Workbook.load(temp_path)
            
            assert loaded.get_sheet(0).root_topic.notes == "These are detailed notes"
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)
    
    def test_labels_persistence(self):
        """Test that labels are saved and loaded correctly."""
        original = Workbook()
        sheet = original.create_sheet()
        root = sheet.get_root_topic()
        root.title = "Root"
        root.add_label("important")
        root.add_label("urgent")
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            original.save(temp_path)
            loaded = Workbook.load(temp_path)
            
            loaded_root = loaded.get_sheet(0).root_topic
            assert "important" in loaded_root.labels
            assert "urgent" in loaded_root.labels
            assert len(loaded_root.labels) == 2
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)
    
    def test_markers_persistence(self):
        """Test that markers are saved and loaded correctly."""
        original = Workbook()
        sheet = original.create_sheet()
        root = sheet.get_root_topic()
        root.title = "Root"
        root.add_marker("priority-1")
        root.add_marker("task-done")
        
        with tempfile.NamedTemporaryFile(suffix='.xmind', delete=False) as f:
            temp_path = f.name
        
        try:
            original.save(temp_path)
            loaded = Workbook.load(temp_path)
            
            loaded_root = loaded.get_sheet(0).root_topic
            assert "priority-1" in loaded_root.markers
            assert "task-done" in loaded_root.markers
            assert len(loaded_root.markers) == 2
        finally:
            if os.path.exists(temp_path):
                os.remove(temp_path)
