#!/usr/bin/env python3
"""Comprehensive Docker operations functional tests.

Tests all Docker client functionality through BlackAnt API.
"""

import sys
import os
import time
import unittest

# Add src to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'src'))

from blackant import BlackAntAuth, BlackAntDockerClient


class TestDockerOperations(unittest.TestCase):
    """Test Docker client operations."""

    @classmethod
    def setUpClass(cls):
        """Set up test environment."""
        # Get credentials from environment variables
        test_user = os.getenv("BLACKANT_TEST_USER", "admin")
        test_password = os.getenv("BLACKANT_TEST_PASSWORD")

        if not test_password:
            raise unittest.SkipTest("BLACKANT_TEST_PASSWORD not set in environment")

        cls.auth = BlackAntAuth(
            user=test_user,
            password=test_password,
            login_url=os.getenv("BLACKANT_LOGIN_URL", "http://localhost/api/auth/login")
        )
        cls.client = BlackAntDockerClient(
            auth=cls.auth,
            base_url=os.getenv("BLACKANT_BASE_URL", "http://localhost")
        )

    def test_version(self):
        """Test Docker version retrieval."""
        version = self.client.version
        self.assertIsInstance(version, str)
        self.assertNotEqual(version, "")
        print(f"Docker version: {version}")

    def test_ping(self):
        """Test Docker ping."""
        result = self.client.ping()
        self.assertTrue(result)

    def test_containers_list(self):
        """Test container listing."""
        containers = self.client.containers()
        self.assertIsInstance(containers, list)

        all_containers = self.client.containers(all_containers=True)
        self.assertIsInstance(all_containers, list)
        self.assertGreaterEqual(len(all_containers), len(containers))

    def test_images_list(self):
        """Test image listing."""
        images = self.client.images()
        self.assertIsInstance(images, list)
        self.assertGreater(len(images), 0)

    def test_services_list(self):
        """Test services listing."""
        services = self.client.services()
        self.assertIsInstance(services, list)
        self.assertGreater(len(services), 0)

    def test_docker_info(self):
        """Test Docker system info."""
        info = self.client.info()
        self.assertIsInstance(info, dict)
        self.assertIn('ServerVersion', info)

    def test_container_inspection(self):
        """Test container inspection."""
        containers = self.client.containers()
        if containers:
            container_id = containers[0]['Id'][:12]
            info = self.client.inspect_container(container_id)
            self.assertIsInstance(info, dict)
            self.assertIn('Id', info)

    def test_container_logs(self):
        """Test container logs retrieval."""
        containers = self.client.containers()
        if containers:
            container_id = containers[0]['Id'][:12]
            logs = self.client.get_container_logs(container_id, tail=5)
            self.assertIsInstance(logs, str)

    def test_system_disk_usage(self):
        """Test Docker system disk usage."""
        df_data = self.client.get_system_df()
        self.assertIsInstance(df_data, dict)

    def test_docker_events(self):
        """Test Docker events retrieval."""
        events = self.client.get_events(since=int(time.time()) - 60)
        self.assertIsInstance(events, list)

    def test_image_inspection(self):
        """Test image inspection."""
        images = self.client.images()
        if images and images[0].get('RepoTags'):
            image_name = images[0]['RepoTags'][0]
            info = self.client.inspect_image(image_name)
            self.assertIsInstance(info, dict)
            self.assertIn('Id', info)

    def test_container_lifecycle(self):
        """Test container creation and removal (safe test)."""
        try:
            # Create test container
            container_id = self.client.create_container(
                image="hello-world",
                name="blackant-test-container"
            )
            self.assertIsInstance(container_id, str)
            self.assertNotEqual(container_id, "")

            # Remove test container
            result = self.client.remove_container(container_id, force=True)
            self.assertTrue(result)

        except Exception as e:
            self.fail(f"Container lifecycle test failed: {e}")


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