#!/usr/bin/env python3
"""Demo script to test build_service functionality."""

import os
import sys
from unittest.mock import Mock

# Add src to path
sys.path.insert(0, 'src')

from blackant.auth.blackant_auth import BlackAntAuth
from blackant.docker.client import BlackAntDockerClient
from blackant.config.docker_config import get_docker_config


def demo_build_service():
    """Demo build_service functionality with mock authentication."""

    print("🚀 BlackAnt SDK build_service() Demo")
    print("=" * 50)

    # 1. Show configuration
    print("\n📋 1. Docker Configuration:")
    config = get_docker_config()
    print(f"   Registry: {config.registry.url}")
    print(f"   Namespace: {config.registry.namespace}")
    print(f"   Build timeout: {config.build.timeout}s")

    # Test image name generation
    test_image = config.get_full_image_name("demo-calc", "v1.0.0-demo")
    print(f"   Example image: {test_image}")

    # 2. Mock authentication (since we don't have real credentials)
    print("\n🔐 2. Mock Authentication Setup:")
    mock_auth = Mock(spec=BlackAntAuth)
    mock_auth.token_store = Mock()
    mock_auth.get_token.return_value = "demo_jwt_token_12345"
    print("   ✅ Mock authentication ready")

    # 3. Check implementation files
    print("\n📁 3. Implementation Files Check:")
    impl_path = "src/calculation/impl"
    dockerfile_path = "Dockerfile"

    if os.path.exists(impl_path):
        files = os.listdir(impl_path)
        print(f"   ✅ Implementation path exists: {impl_path}")
        print(f"   Files: {files}")
    else:
        print(f"   ❌ Implementation path missing: {impl_path}")
        return False

    if os.path.exists(dockerfile_path):
        print(f"   ✅ Dockerfile exists: {dockerfile_path}")
    else:
        print(f"   ❌ Dockerfile missing: {dockerfile_path}")
        return False

    # 4. Show what build_service would do (without actual Docker build)
    print("\n🔧 4. build_service() Workflow Preview:")

    service_name = "demo-calculation"
    tag = "v1.0.0-demo"

    print(f"   Service name: {service_name}")
    print(f"   Tag: {tag}")
    print(f"   Implementation path: {impl_path}")
    print(f"   Dockerfile: {dockerfile_path}")

    # Generate expected service config
    expected_config = {
        "name": service_name,
        "type": "calculation",
        "image": {
            "container": "systemdevelopers",
            "name": service_name,
            "tag": tag
        },
        "environments": {
            "BLACKANT_ENV": "production",
            "LOG_LEVEL": "INFO",
            "SERVICE_NAME": service_name
        },
        "networks": ["blackant_network"],
        "parent": None,
        "resource_config": {
            "use_gpu": False,
            "cpu_limit": 1.0,
            "ram_limit": "512M",
            "disk_limit": "1G",
            "node_label": None
        }
    }

    print("\n📦 5. Expected ServiceManager Configuration:")
    import json
    print(json.dumps(expected_config, indent=2))

    # 6. Show expected API call
    print("\n🌐 6. Expected ServiceManager API Call:")
    print(f"   POST /api/v1/services")
    print(f"   Content-Type: application/json")
    print(f"   Authorization: Bearer {mock_auth.get_token()}")
    print(f"   Body: [ServiceConfig as shown above]")

    # 7. Expected results
    print("\n📊 7. Expected build_service() Result:")
    expected_result = {
        "image_name": f"env.blackant.app/systemdevelopers/{service_name}",
        "tag": tag,
        "full_image": f"env.blackant.app/systemdevelopers/{service_name}:{tag}",
        "image_id": "sha256:demo123456789...",
        "size": 125000000,
        "pushed": True,
        "registry_url": "env.blackant.app",
        "service_id": "uuid-from-servicemanager",
        "service_registered": True,
        "build_success": True
    }

    print(json.dumps(expected_result, indent=2))

    print("\n✅ Demo completed successfully!")
    print("\n💡 To run actual build_service():")
    print("   client = BlackAntDockerClient(auth=real_auth)")
    print(f"   result = client.build_service('{service_name}')")

    return True


def demo_client_usage():
    """Demo how to use BlackAntDockerClient.build_service()."""

    print("\n" + "="*60)
    print("📖 build_service() Usage Examples")
    print("="*60)

    examples = [
        {
            "title": "Basic Usage",
            "code": '''
# Basic service build with defaults
auth = BlackAntAuth(user="developer@company.com", password="xxx")
client = BlackAntDockerClient(auth=auth)

result = client.build_service("my-calculation")
print(f"Service ID: {result['service_id']}")
print(f"Image: {result['full_image']}")
'''
        },
        {
            "title": "Custom Configuration",
            "code": '''
# Custom paths and configuration
result = client.build_service(
    service_name="advanced-calc",
    impl_path="custom/impl/path",
    dockerfile_path="custom/Dockerfile",
    tag="v2.1.0-prod",
    push=True,
    register_service=True
)
'''
        },
        {
            "title": "Local Development",
            "code": '''
# Build without pushing to registry (local development)
result = client.build_service(
    service_name="dev-calc",
    push=False,
    register_service=False
)
print(f"Local image: {result['image_id']}")
'''
        },
        {
            "title": "Error Handling",
            "code": '''
# Proper error handling
try:
    result = client.build_service("my-calc")
    if result['service_registered']:
        print(f"✅ Service deployed: {result['service_id']}")
    else:
        print("⚠️ Build succeeded but registration failed")
except BlackAntDockerError as e:
    print(f"❌ Build failed: {e}")
'''
        }
    ]

    for i, example in enumerate(examples, 1):
        print(f"\n{i}. {example['title']}:")
        print("-" * (len(example['title']) + 3))
        print(example['code'])


if __name__ == "__main__":
    success = demo_build_service()
    if success:
        demo_client_usage()

    print(f"\n🎯 Demo script completed!")
    print(f"📁 Project structure ready for build_service() implementation!")