#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test script for template manager functionality
"""

import os
import json
import shutil
import tempfile
from pathlib import Path

def create_test_template(template_dir: Path, template_name: str):
    """Create a test template with draft_content.json"""
    
    # Create template directory
    template_path = template_dir / template_name
    template_path.mkdir(parents=True, exist_ok=True)
    
    # Create sample draft_content.json
    draft_content = {
        "version": "1.0",
        "canvas_config": {
            "width": 1920,
            "height": 1080,
            "fps": 30
        },
        "duration": 5000000,  # 5 seconds in microseconds
        "tracks": [
            {
                "id": "track_1",
                "type": "video",
                "segments": [
                    {
                        "id": "segment_1",
                        "material_id": "video_1",
                        "source_timerange": {"start": 0, "end": 3000000},
                        "target_timerange": {"start": 0, "end": 3000000}
                    }
                ]
            },
            {
                "id": "track_2", 
                "type": "audio",
                "segments": [
                    {
                        "id": "segment_2",
                        "material_id": "audio_1",
                        "source_timerange": {"start": 0, "end": 5000000},
                        "target_timerange": {"start": 0, "end": 5000000}
                    }
                ]
            }
        ],
        "materials": {
            "videos": [
                {
                    "id": "video_1",
                    "name": "sample_video.mp4",
                    "path": str(template_path / "sample_video.mp4"),
                    "duration": 3000000,
                    "width": 1920,
                    "height": 1080
                }
            ],
            "audios": [
                {
                    "id": "audio_1", 
                    "name": "sample_audio.mp3",
                    "path": str(template_path / "sample_audio.mp3"),
                    "duration": 5000000
                }
            ],
            "images": [
                {
                    "id": "image_1",
                    "name": "sample_image.jpg", 
                    "path": str(template_path / "sample_image.jpg"),
                    "width": 1920,
                    "height": 1080
                }
            ]
        }
    }
    
    # Save draft_content.json
    with open(template_path / "draft_content.json", 'w', encoding='utf-8') as f:
        json.dump(draft_content, f, ensure_ascii=False, indent=2)
    
    # Create dummy media files
    (template_path / "sample_video.mp4").touch()
    (template_path / "sample_audio.mp3").touch()
    (template_path / "sample_image.jpg").touch()
    
    print(f"Created test template: {template_name}")
    return template_path

def test_template_manager():
    """Test the template manager functionality"""
    
    # Create temporary directory for test templates
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        
        print(f"Creating test templates in: {temp_path}")
        
        # Create multiple test templates
        templates = [
            "Wedding_Template",
            "Birthday_Template", 
            "Corporate_Template",
            "Travel_Template"
        ]
        
        for template_name in templates:
            create_test_template(temp_path, template_name)
        
        # Test the template manager
        print("\nTesting template manager...")
        
        try:
            from python_core.services.template_manager import TemplateManager
            
            manager = TemplateManager()
            
            # Test batch import
            print("Testing batch import...")
            result = manager.batch_import_templates(str(temp_path))
            
            print(f"Import result: {result}")
            
            if result['status']:
                print(f"Successfully imported {result['imported_count']} templates")
                
                # Test get templates
                print("\nTesting get templates...")
                templates = manager.get_templates()
                print(f"Found {len(templates)} templates")
                
                for template in templates:
                    print(f"  - {template.name} (ID: {template.id})")
                    print(f"    Duration: {template.duration/1000000:.1f}s")
                    print(f"    Materials: {template.material_count}")
                    print(f"    Tracks: {template.track_count}")
                
                # Test get specific template
                if templates:
                    template_id = templates[0].id
                    print(f"\nTesting get specific template: {template_id}")
                    template = manager.get_template(template_id)
                    if template:
                        print(f"Retrieved template: {template.name}")
                    else:
                        print("Failed to retrieve template")
                
                # Test delete template
                if templates:
                    template_id = templates[0].id
                    print(f"\nTesting delete template: {template_id}")
                    success = manager.delete_template(template_id)
                    if success:
                        print("Template deleted successfully")
                        
                        # Verify deletion
                        remaining_templates = manager.get_templates()
                        print(f"Remaining templates: {len(remaining_templates)}")
                    else:
                        print("Failed to delete template")
            else:
                print(f"Import failed: {result['msg']}")
                
        except Exception as e:
            print(f"Error testing template manager: {e}")
            import traceback
            traceback.print_exc()

def test_command_line():
    """Test the command line interface"""
    
    print("\nTesting command line interface...")
    
    # Create temporary directory for test templates
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        
        # Create a test template
        create_test_template(temp_path, "CLI_Test_Template")
        
        # Test CLI commands
        import subprocess
        import sys
        
        try:
            # Test batch import
            print("Testing CLI batch import...")
            result = subprocess.run([
                sys.executable, "-m", "python_core.services.template_manager",
                "--action", "batch_import",
                "--source_folder", str(temp_path)
            ], capture_output=True, text=True, cwd=".")
            
            print(f"CLI Exit code: {result.returncode}")
            print(f"CLI Stdout: {result.stdout}")
            if result.stderr:
                print(f"CLI Stderr: {result.stderr}")
            
            if result.returncode == 0:
                # Parse result
                import json
                cli_result = json.loads(result.stdout)
                print(f"CLI Import result: {cli_result}")
                
                # Test get templates
                print("\nTesting CLI get templates...")
                result = subprocess.run([
                    sys.executable, "-m", "python_core.services.template_manager",
                    "--action", "get_templates"
                ], capture_output=True, text=True, cwd=".")
                
                if result.returncode == 0:
                    templates_result = json.loads(result.stdout)
                    print(f"CLI Templates: {len(templates_result.get('templates', []))}")
                else:
                    print(f"CLI get templates failed: {result.stderr}")
            else:
                print("CLI batch import failed")
                
        except Exception as e:
            print(f"Error testing CLI: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    print("Template Manager Test Script")
    print("=" * 50)
    
    # Test the template manager class
    test_template_manager()
    
    # Test the command line interface
    test_command_line()
    
    print("\nTest completed!")
