"""
Test AI migration functionality.
"""
import unittest
import json
import tempfile
import os
from unittest.mock import Mock, patch, MagicMock
from onepasswd.models import PasswordEntry


class TestAIMigration(unittest.TestCase):
    """Test AI migration functionality."""

    def setUp(self):
        """Set up test fixtures."""
        self.temp_dir = tempfile.mkdtemp()

    def test_extract_entry_metadata(self):
        """Test metadata extraction without password."""
        try:
            from onepasswd.ai_migrate import AIPasswordMigrator
        except ImportError:
            self.skipTest("OpenAI SDK not installed")

        entry = PasswordEntry(
            entries=['github', 'work'],
            passwd='encrypted_password',
            title='GitHub Work Account',
            url='https://github.com',
            username='user@company.com'
        )

        # Mock the OpenAI client
        with patch('onepasswd.ai_migrate.OpenAI'):
            migrator = AIPasswordMigrator(api_key='test_key')
            metadata = migrator.extract_entry_metadata(entry)

        # Verify password is not included
        self.assertNotIn('passwd', metadata)
        self.assertEqual(metadata['keywords'], ['github', 'work'])
        self.assertEqual(metadata['title'], 'GitHub Work Account')
        self.assertEqual(metadata['url'], 'https://github.com')
        self.assertEqual(metadata['username'], 'user@company.com')

    def test_identify_missing_fields(self):
        """Test identification of missing fields."""
        try:
            from onepasswd.ai_migrate import AIPasswordMigrator
        except ImportError:
            self.skipTest("OpenAI SDK not installed")

        # Mock the OpenAI client
        with patch('onepasswd.ai_migrate.OpenAI'):
            migrator = AIPasswordMigrator(api_key='test_key')

        # Entry with missing fields
        metadata = {
            'keywords': ['github'],
            'title': 'GitHub',
            'url': None,
            'username': '',
            'description': None,
            'category': None,
            'tags': []
        }

        missing = migrator.identify_missing_fields(metadata)

        # Should identify missing fields
        self.assertIn('url', missing)
        self.assertIn('username', missing)
        self.assertIn('description', missing)
        self.assertIn('category', missing)
        self.assertIn('tags', missing)
        self.assertNotIn('title', missing)  # title is present

    def test_build_ai_prompt(self):
        """Test AI prompt generation."""
        try:
            from onepasswd.ai_migrate import AIPasswordMigrator
        except ImportError:
            self.skipTest("OpenAI SDK not installed")

        # Mock the OpenAI client
        with patch('onepasswd.ai_migrate.OpenAI'):
            migrator = AIPasswordMigrator(api_key='test_key')

        entries = [
            {
                'keywords': ['github', 'work'],
                'title': 'GitHub',
                'url': None,
                'username': None,
                'category': None,
                'description': None,
                'tags': []
            }
        ]

        prompt = migrator.build_ai_prompt(entries, user_context="Work accounts")

        # Verify prompt contains key elements
        self.assertIn('github', prompt.lower())
        self.assertIn('work', prompt.lower())
        self.assertIn('Work accounts', prompt)
        self.assertIn('JSON', prompt)

    def test_generate_review_file(self):
        """Test review file generation."""
        try:
            from onepasswd.ai_migrate import AIPasswordMigrator
        except ImportError:
            self.skipTest("OpenAI SDK not installed")

        # Mock the OpenAI client
        with patch('onepasswd.ai_migrate.OpenAI'):
            migrator = AIPasswordMigrator(api_key='test_key')

        results = {
            'total_processed': 2,
            'entries': [
                {
                    'original': {
                        'keywords': ['github'],
                        'title': None,
                        'url': None
                    },
                    'proposed': {
                        'title': 'GitHub',
                        'url': 'https://github.com',
                        'category': 'Development'
                    },
                    'missing_fields': ['title', 'url', 'category']
                }
            ]
        }

        output_path = os.path.join(self.temp_dir, 'review.json')
        review_path = migrator.generate_review_file(results, output_path=output_path)

        # Verify file was created
        self.assertTrue(os.path.exists(review_path))

        # Verify file contents
        with open(review_path, 'r') as f:
            review_data = json.load(f)

        self.assertEqual(review_data['total_entries'], 2)
        self.assertEqual(len(review_data['entries']), 1)
        self.assertIn('instructions', review_data)

        entry = review_data['entries'][0]
        self.assertEqual(entry['keywords'], ['github'])
        self.assertTrue(entry['approved'])
        self.assertIn('proposed', entry)

    def test_check_openai_available(self):
        """Test OpenAI availability check."""
        from onepasswd.ai_migrate import check_openai_available

        # This will return True if openai is installed, False otherwise
        result = check_openai_available()
        self.assertIsInstance(result, bool)


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