"""
PM-Agent More Coverage Tests
"""

import pytest
import os
import sys
import tempfile
import shutil
from pathlib import Path
from unittest.mock import Mock, patch

sys.path.insert(0, str(Path(__file__).parent.parent))


class TestMoreCoverage:
    """More tests to push coverage"""
    
    def test_customer_get(self):
        """Test customer get"""
        from backend.services.customer_service import CustomerService
        from backend.models.database import SessionLocal
        db = SessionLocal()
        s = CustomerService(db)
        try:
            s.get_by_id(1)
            s.get_by_name("test")
            s.list_all(False)
        finally:
            db.close()
    
    def test_customer_ops(self):
        """Test customer operations"""
        from backend.services.customer_service import CustomerService
        from backend.models.database import SessionLocal
        db = SessionLocal()
        s = CustomerService(db)
        try:
            c = s.match("test")
            if c:
                s.update(c.id, name="updated")
                s.delete(c.id)
        finally:
            db.close()
    
    def test_project_ops(self):
        """Test project operations"""
        from backend.services.project_service import ProjectService
        from backend.models.database import SessionLocal
        db = SessionLocal()
        s = ProjectService(db)
        try:
            p = s.match("test")
            if p:
                s.update(p.id, name="updated")
                s.update_progress(p.id, 50)
                s.update_status(p.id, "active")
                s.delete(p.id)
        finally:
            db.close()
    
    def test_project_list(self):
        """Test project list"""
        from backend.services.project_service import ProjectService
        from backend.models.database import SessionLocal
        db = SessionLocal()
        s = ProjectService(db)
        try:
            s.list_all(1, False)
            s.list_all(None, True)
        finally:
            db.close()
    
    def test_processing_log(self):
        """Test processing log"""
        from backend.services.processing_log_service import ProcessingLogService
        from backend.models.database import SessionLocal
        db = SessionLocal()
        s = ProcessingLogService(db)
        try:
            s.create(input_type="text", content="test")
            s.get_by_id(1)
            s.get_recent(10)
            s.get_pending(1)
            s.mark_synced(1)
        finally:
            db.close()
    
    def test_progress(self):
        """Test progress"""
        from backend.services.progress_service import ProgressService, ProjectProgress, RequirementsProgress, BugsProgress, TodosProgress
        from unittest.mock import Mock
        
        mock_client = Mock()
        mock_client.list_projects.return_value = []
        
        s = ProgressService(client=mock_client)
        
        p = ProjectProgress(
            project_name="test",
            requirements=RequirementsProgress(total=0, completed=0),
            bugs=BugsProgress(total=0, resolved=0),
            todos=TodosProgress(total=0, completed=0)
        )
        
        s.calculate_overall_progress(p)
        s.get_all_projects_summary()
    
    def test_status(self):
        """Test status"""
        from backend.services.status_feedback_service import StatusFeedbackService
        from unittest.mock import Mock
        
        s = StatusFeedbackService()
        
        s._get_active_project_names()
        s.get_change_history("p")
        s.check_status_changes("p")
    
    def test_sync_permission(self):
        """Test sync permission"""
        from backend.services.sync_permission_service import SyncPermissionService
        
        s = SyncPermissionService()
        s.can_auto_sync()
        s.get_confidential_projects_summary()
    
    def test_doc_fetcher(self):
        """Test document fetcher"""
        from backend.services.document_fetcher import DocumentFetcher
        
        temp = tempfile.mkdtemp()
        try:
            with open(os.path.join(temp, "test.md"), "w") as f:
                f.write("# Test")
            
            f = DocumentFetcher(base_path=temp)
            f.fetch_docs(temp)
            f.search("test", os.path.basename(temp))
            f.get_doc_content(os.path.basename(temp), "test.md")
            f.list_doc_categories(temp)
        finally:
            shutil.rmtree(temp, ignore_errors=True)
    
    def test_input_handler(self):
        """Test input handler"""
        from backend.services.input_handler import InputHandler
        
        h = InputHandler()
        
        h.detect_type("test.png")
        h.detect_type("test.mp3")
        h.detect_type("test.pdf")
        h.detect_type("test.json")
        h.detect_type("test.xyz")
    
    def test_git_service(self):
        """Test git service"""
        from backend.services.git_service import GitService
        
        temp = tempfile.mkdtemp()
        try:
            s = GitService(temp)
            
            s._format_requirement({'title': 't', 'id': '1', 'p': 'p'})
            
            with open(os.path.join(temp, "test.md"), "w") as f:
                f.write("# Test")
            
            s.fetch_development_docs(temp)
            s.check_requirement_completed(temp, "REQ-001")
        finally:
            shutil.rmtree(temp, ignore_errors=True)


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
