"""
Template management system for video overlays
"""

import logging
from typing import Dict, Any, Optional, List
from pathlib import Path
import json

logger = logging.getLogger(__name__)


class TemplateManager:
    """Manages overlay templates"""
    
    def __init__(self):
        self.templates: Dict[str, Dict[str, Any]] = {}
        self._load_built_in_templates()
    
    def _load_built_in_templates(self):
        """Load built-in templates"""
        try:
            # News template
            self.templates['news_template'] = NewsTemplate().get_config()
            
            # Sports template
            self.templates['sports_template'] = SportsTemplate().get_config()
            
            # Simple template
            self.templates['simple_template'] = SimpleTemplate().get_config()
            
            logger.info(f"Loaded {len(self.templates)} built-in templates")
            
        except Exception as e:
            logger.error(f"Failed to load built-in templates: {e}")
    
    def get_template(self, template_name: str) -> Optional[Dict[str, Any]]:
        """Get template configuration by name"""
        return self.templates.get(template_name)
    
    def register_template(self, name: str, template_config: Dict[str, Any]):
        """Register a new template"""
        self.templates[name] = template_config
        logger.info(f"Registered template: {name}")
    
    def get_template_names(self) -> List[str]:
        """Get list of available template names"""
        return list(self.templates.keys())
    
    def load_template_from_file(self, file_path: str) -> Optional[Dict[str, Any]]:
        """Load template from JSON file"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                template_config = json.load(f)
            
            # Validate template
            if self._validate_template(template_config):
                return template_config
            else:
                logger.error(f"Invalid template in file: {file_path}")
                return None
                
        except Exception as e:
            logger.error(f"Failed to load template from {file_path}: {e}")
            return None
    
    def save_template_to_file(self, template_config: Dict[str, Any], file_path: str) -> bool:
        """Save template to JSON file"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(template_config, f, indent=2, ensure_ascii=False)
            
            logger.info(f"Template saved to {file_path}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to save template to {file_path}: {e}")
            return False
    
    def _validate_template(self, template_config: Dict[str, Any]) -> bool:
        """Validate template configuration"""
        try:
            # Check required fields
            required_fields = ['name', 'layout', 'elements']
            for field in required_fields:
                if field not in template_config:
                    logger.error(f"Template missing required field: {field}")
                    return False
            
            # Validate layout
            layout = template_config['layout']
            if not isinstance(layout, dict):
                logger.error("Template layout must be a dictionary")
                return False
            
            if 'width' not in layout or 'height' not in layout:
                logger.error("Template layout must specify width and height")
                return False
            
            # Validate elements
            elements = template_config['elements']
            if not isinstance(elements, list):
                logger.error("Template elements must be a list")
                return False
            
            for element in elements:
                if not self._validate_element(element):
                    return False
            
            return True
            
        except Exception as e:
            logger.error(f"Template validation error: {e}")
            return False
    
    def _validate_element(self, element: Dict[str, Any]) -> bool:
        """Validate template element"""
        try:
            # Check required fields
            required_fields = ['id', 'type']
            for field in required_fields:
                if field not in element:
                    logger.error(f"Element missing required field: {field}")
                    return False
            
            # Check element type
            valid_types = ['rectangle', 'text', 'image']
            if element['type'] not in valid_types:
                logger.error(f"Invalid element type: {element['type']}")
                return False
            
            return True
            
        except Exception as e:
            logger.error(f"Element validation error: {e}")
            return False


class BaseTemplate:
    """Base class for templates"""
    
    def __init__(self, name: str, width: int = 1920, height: int = 1080):
        self.name = name
        self.width = width
        self.height = height
        self.elements = []
    
    def get_config(self) -> Dict[str, Any]:
        """Get template configuration"""
        return {
            'name': self.name,
            'layout': {
                'width': self.width,
                'height': self.height
            },
            'elements': self.elements
        }
    
    def add_element(self, element: Dict[str, Any]):
        """Add element to template"""
        self.elements.append(element)


class NewsTemplate(BaseTemplate):
    """News-style template with scrolling text and boxing athletes image"""
    
    def __init__(self):
        super().__init__('news_template', 1920, 1080)
        self._create_elements()
    
    def _create_elements(self):
        """Create news template elements"""
        # News bar background
        self.add_element({
            'id': 'news_bar',
            'type': 'rectangle',
            'x': 0,
            'y': 950,
            'width': 1920,
            'height': 130,
            'color': '#1a1a1a',
            'opacity': 0.9,
            'border_width': 2,
            'border_color': '#333333',
            'z_index': 1
        })
        
        # Boxing athletes image
        self.add_element({
            'id': 'athlete_image',
            'type': 'image',
            'x': 50,
            'y': 960,
            'width': 110,
            'height': 110,
            'source': 'assets/boxing_athletes.png',
            'fit': 'cover',
            'z_index': 2
        })
        
        # Scrolling news text
        self.add_element({
            'id': 'scrolling_text',
            'type': 'text',
            'x': 180,
            'y': 985,
            'width': 1500,
            'height': 50,
            'text': 'Breaking News: Boxing Match Updates • Live from the Arena',
            'font_family': 'Arial',
            'font_size': 28,
            'font_weight': 'bold',
            'color': '#ffffff',
            'background_color': 'transparent',
            'alignment': 'left',
            'animation': {
                'type': 'scroll',
                'direction': 'left',
                'speed': 120
            },
            'z_index': 3
        })
        
        # News ticker separator
        self.add_element({
            'id': 'ticker_separator',
            'type': 'text',
            'x': 180,
            'y': 1030,
            'width': 1600,
            'height': 35,
            'text': '• LIVE • BREAKING NEWS • SPORTS UPDATE •',
            'font_family': 'Arial',
            'font_size': 18,
            'font_weight': 'normal',
            'color': '#ffcc00',
            'background_color': 'transparent',
            'alignment': 'left',
            'animation': {
                'type': 'scroll',
                'direction': 'left',
                'speed': 80
            },
            'z_index': 3
        })
        
        # Optional logo area
        self.add_element({
            'id': 'logo_area',
            'type': 'rectangle',
            'x': 1750,
            'y': 960,
            'width': 150,
            'height': 110,
            'color': '#333333',
            'opacity': 0.8,
            'border_width': 1,
            'border_color': '#555555',
            'z_index': 2
        })
        
        # Logo text placeholder
        self.add_element({
            'id': 'logo_text',
            'type': 'text',
            'x': 1750,
            'y': 1000,
            'width': 150,
            'height': 30,
            'text': 'MBETTER',
            'font_family': 'Arial',
            'font_size': 16,
            'font_weight': 'bold',
            'color': '#ffffff',
            'alignment': 'center',
            'z_index': 3
        })


class SportsTemplate(BaseTemplate):
    """Sports-focused template"""
    
    def __init__(self):
        super().__init__('sports_template', 1920, 1080)
        self._create_elements()
    
    def _create_elements(self):
        """Create sports template elements"""
        # Score bar
        self.add_element({
            'id': 'score_bar',
            'type': 'rectangle',
            'x': 0,
            'y': 50,
            'width': 1920,
            'height': 80,
            'color': '#0066cc',
            'opacity': 0.9,
            'z_index': 1
        })
        
        # Team scores
        self.add_element({
            'id': 'team_scores',
            'type': 'text',
            'x': 50,
            'y': 60,
            'width': 1820,
            'height': 60,
            'text': 'TEAM A  2  -  1  TEAM B',
            'font_family': 'Arial',
            'font_size': 36,
            'font_weight': 'bold',
            'color': '#ffffff',
            'alignment': 'center',
            'z_index': 2
        })
        
        # Match time
        self.add_element({
            'id': 'match_time',
            'type': 'text',
            'x': 1700,
            'y': 20,
            'width': 200,
            'height': 30,
            'text': '45:30',
            'font_family': 'Arial',
            'font_size': 24,
            'font_weight': 'bold',
            'color': '#ffcc00',
            'alignment': 'center',
            'z_index': 2
        })


class SimpleTemplate(BaseTemplate):
    """Simple template with minimal overlay"""
    
    def __init__(self):
        super().__init__('simple_template', 1920, 1080)
        self._create_elements()
    
    def _create_elements(self):
        """Create simple template elements"""
        # Simple text overlay
        self.add_element({
            'id': 'simple_text',
            'type': 'text',
            'x': 50,
            'y': 50,
            'width': 800,
            'height': 60,
            'text': 'MbetterClient Video Player',
            'font_family': 'Arial',
            'font_size': 32,
            'font_weight': 'bold',
            'color': '#ffffff',
            'background_color': 'rgba(0, 0, 0, 128)',
            'alignment': 'left',
            'z_index': 1
        })
        
        # Timestamp
        self.add_element({
            'id': 'timestamp',
            'type': 'text',
            'x': 1520,
            'y': 50,
            'width': 350,
            'height': 40,
            'text': '2024-01-01 12:00:00',
            'font_family': 'Arial',
            'font_size': 18,
            'font_weight': 'normal',
            'color': '#cccccc',
            'alignment': 'right',
            'z_index': 1
        })


class TemplateBuilder:
    """Helper class for building custom templates"""
    
    def __init__(self, name: str, width: int = 1920, height: int = 1080):
        self.template = BaseTemplate(name, width, height)
    
    def add_rectangle(self, element_id: str, x: int, y: int, width: int, height: int,
                     color: str = '#000000', opacity: float = 1.0, **kwargs) -> 'TemplateBuilder':
        """Add rectangle element"""
        element = {
            'id': element_id,
            'type': 'rectangle',
            'x': x,
            'y': y,
            'width': width,
            'height': height,
            'color': color,
            'opacity': opacity,
            **kwargs
        }
        self.template.add_element(element)
        return self
    
    def add_text(self, element_id: str, x: int, y: int, width: int, height: int,
                text: str, font_size: int = 16, color: str = '#ffffff', **kwargs) -> 'TemplateBuilder':
        """Add text element"""
        element = {
            'id': element_id,
            'type': 'text',
            'x': x,
            'y': y,
            'width': width,
            'height': height,
            'text': text,
            'font_size': font_size,
            'color': color,
            **kwargs
        }
        self.template.add_element(element)
        return self
    
    def add_image(self, element_id: str, x: int, y: int, width: int, height: int,
                 source: str, fit: str = 'contain', **kwargs) -> 'TemplateBuilder':
        """Add image element"""
        element = {
            'id': element_id,
            'type': 'image',
            'x': x,
            'y': y,
            'width': width,
            'height': height,
            'source': source,
            'fit': fit,
            **kwargs
        }
        self.template.add_element(element)
        return self
    
    def add_scrolling_text(self, element_id: str, x: int, y: int, width: int, height: int,
                          text: str, speed: int = 100, direction: str = 'left', **kwargs) -> 'TemplateBuilder':
        """Add scrolling text element"""
        element = {
            'id': element_id,
            'type': 'text',
            'x': x,
            'y': y,
            'width': width,
            'height': height,
            'text': text,
            'animation': {
                'type': 'scroll',
                'direction': direction,
                'speed': speed
            },
            **kwargs
        }
        self.template.add_element(element)
        return self
    
    def build(self) -> Dict[str, Any]:
        """Build and return template configuration"""
        return self.template.get_config()


# Template presets for easy customization
NEWS_TEMPLATE_PRESET = {
    'bar_height': 130,
    'bar_opacity': 0.9,
    'bar_color': '#1a1a1a',
    'text_color': '#ffffff',
    'accent_color': '#ffcc00',
    'font_family': 'Arial',
    'main_font_size': 28,
    'ticker_font_size': 18,
    'scroll_speed': 120,
    'image_size': 110
}

SPORTS_TEMPLATE_PRESET = {
    'bar_height': 80,
    'bar_color': '#0066cc',
    'text_color': '#ffffff',
    'accent_color': '#ffcc00',
    'font_family': 'Arial',
    'score_font_size': 36,
    'time_font_size': 24
}


def create_custom_news_template(preset: Dict[str, Any] = None) -> Dict[str, Any]:
    """Create customized news template using preset values"""
    if preset is None:
        preset = NEWS_TEMPLATE_PRESET
    
    builder = TemplateBuilder('custom_news_template')
    
    # News bar
    builder.add_rectangle(
        'news_bar', 0, 1080 - preset['bar_height'], 1920, preset['bar_height'],
        color=preset['bar_color'], opacity=preset['bar_opacity']
    )
    
    # Boxing athletes image
    builder.add_image(
        'athlete_image', 50, 1080 - preset['bar_height'] + 10,
        preset['image_size'], preset['image_size'],
        source='assets/boxing_athletes.png', fit='cover'
    )
    
    # Scrolling text
    builder.add_scrolling_text(
        'scrolling_text', 50 + preset['image_size'] + 20, 1080 - preset['bar_height'] + 25,
        1400, 50, text='Breaking News: Boxing Match Updates',
        speed=preset['scroll_speed'], font_size=preset['main_font_size'],
        color=preset['text_color'], font_family=preset['font_family'], font_weight='bold'
    )
    
    return builder.build()


def create_custom_sports_template(preset: Dict[str, Any] = None) -> Dict[str, Any]:
    """Create customized sports template using preset values"""
    if preset is None:
        preset = SPORTS_TEMPLATE_PRESET
    
    builder = TemplateBuilder('custom_sports_template')
    
    # Score bar
    builder.add_rectangle(
        'score_bar', 0, 50, 1920, preset['bar_height'],
        color=preset['bar_color'], opacity=0.9
    )
    
    # Team scores
    builder.add_text(
        'team_scores', 50, 60, 1820, 60,
        text='TEAM A  0  -  0  TEAM B',
        font_size=preset['score_font_size'], color=preset['text_color'],
        font_family=preset['font_family'], font_weight='bold', alignment='center'
    )
    
    # Match time
    builder.add_text(
        'match_time', 1700, 20, 200, 30,
        text='00:00', font_size=preset['time_font_size'],
        color=preset['accent_color'], font_family=preset['font_family'],
        font_weight='bold', alignment='center'
    )
    
    return builder.build()