#!/usr/bin/env python3
"""
Initialize a new slideshow project with full-control CMS architecture.
Creates modular structure with Content API, Asset API, Style Guide Engine, and Layout Engine.
"""
import os
import sys
import json
import argparse
from pathlib import Path

def create_directory_structure(project_path):
    """Create the complete project directory structure."""
    dirs = [
        'content/extracted',
        'content/templates', 
        'assets/images',
        'assets/icons',
        'assets/media',
        'styles',
        'scripts/apis',
        'scripts/engines',
        'scripts/generators',
        'dist'
    ]
    
    for dir_path in dirs:
        Path(project_path / dir_path).mkdir(parents=True, exist_ok=True)
        
def create_content_api(project_path):
    """Create the Content API structure and templates."""
    
    # Base content structure template
    content_template = {
        "metadata": {
            "title": "New Slideshow",
            "brand": "custom",
            "theme": "default",
            "version": "1.0"
        },
        "slides": []
    }
    
    # Sample slide templates
    slide_templates = {
        "title": {
            "id": "slide-title",
            "type": "title", 
            "content": {
                "headline": "Presentation Title",
                "subline": "Subtitle or tagline"
            },
            "layout": {
                "alignment": "center",
                "background": "default"
            }
        },
        "content": {
            "id": "slide-content",
            "type": "content",
            "content": {
                "headline": "Content Slide",
                "body": "Main content body text",
                "bullets": ["Point 1", "Point 2", "Point 3"]
            },
            "layout": {
                "alignment": "left",
                "columns": 1
            }
        },
        "image": {
            "id": "slide-image",
            "type": "image",
            "content": {
                "headline": "Image Slide",
                "image": "assets/images/placeholder.jpg",
                "caption": "Image caption"
            },
            "layout": {
                "image_position": "center",
                "text_overlay": False
            }
        }
    }
    
    # Write templates
    with open(project_path / 'content/content.json', 'w') as f:
        json.dump(content_template, f, indent=2)
        
    with open(project_path / 'content/templates/slide-templates.json', 'w') as f:
        json.dump(slide_templates, f, indent=2)

def create_brand_presets(project_path, brand):
    """Create brand preset configurations."""
    
    brands = {
        "ce": {
            "name": "CE Brand",
            "typography": {
                "primary": "Inter",
                "secondary": "JetBrains Mono", 
                "weights": [300, 400, 500],
                "heading_sizes": ["3rem", "2rem", "1.5rem"],
                "body_size": "1rem"
            },
            "colors": {
                "primary": "#cc0000",
                "black": "#1a1a1a", 
                "grey": "#666666",
                "light": "#999999",
                "border": "#eeeeee",
                "bg": "#ffffff"
            },
            "layout": {
                "spacing_unit": "8px",
                "max_width": "1200px",
                "border_radius": "4px",
                "constraints": [
                    "no-gradients",
                    "no-shadows", 
                    "no-border-radius-over-4px",
                    "no-font-weight-over-500"
                ]
            }
        },
        "phat": {
            "name": "PHAT Foods",
            "typography": {
                "primary": "Custom Display",
                "secondary": "Inter",
                "weights": [300, 400, 500, 600],
                "heading_sizes": ["4rem", "2.5rem", "1.8rem"],
                "body_size": "1.1rem"
            },
            "colors": {
                "primary": "#D4AF37",  # Liquid gold
                "secondary": "#1A1A1A",
                "accent": "#8B4513",   # Rich brown
                "text": "#2C2C2C",
                "bg": "#FFFEF7"       # Warm white
            },
            "layout": {
                "spacing_unit": "12px",
                "max_width": "1400px", 
                "border_radius": "8px",
                "style": "luxury",
                "hierarchy": "generous"
            }
        },
        "custom": {
            "name": "Custom Brand",
            "typography": {
                "primary": "Inter",
                "secondary": "system-ui",
                "weights": [400, 500],
                "heading_sizes": ["2.5rem", "2rem", "1.5rem"],
                "body_size": "1rem"
            },
            "colors": {
                "primary": "#000000",
                "secondary": "#666666",
                "bg": "#ffffff"
            },
            "layout": {
                "spacing_unit": "8px",
                "max_width": "1200px"
            }
        }
    }
    
    brand_config = brands.get(brand, brands["custom"])
    
    with open(project_path / 'styles/brand-config.json', 'w') as f:
        json.dump(brand_config, f, indent=2)

def create_core_scripts(project_path):
    """Create the core API and engine scripts."""
    
    # Content API script
    content_api = '''#!/usr/bin/env python3
"""Content API - Handle content from any source."""
import json
import sys
from pathlib import Path

class ContentAPI:
    def __init__(self, project_path):
        self.project_path = Path(project_path)
        self.content_file = self.project_path / 'content/content.json'
        
    def load_content(self):
        """Load existing content structure."""
        if self.content_file.exists():
            with open(self.content_file) as f:
                return json.load(f)
        return {"metadata": {}, "slides": []}
    
    def add_slide(self, slide_data):
        """Add a new slide to the presentation."""
        content = self.load_content()
        content["slides"].append(slide_data)
        self.save_content(content)
        
    def save_content(self, content):
        """Save content structure."""
        with open(self.content_file, 'w') as f:
            json.dump(content, f, indent=2)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python content_api.py <project_path>")
        sys.exit(1)
    
    api = ContentAPI(sys.argv[1])
    content = api.load_content()
    print(json.dumps(content, indent=2))
'''
    
    # Asset API script
    asset_api = '''#!/usr/bin/env python3
"""Asset API - Handle assets from any source."""
import os
import shutil
import json
from pathlib import Path

class AssetAPI:
    def __init__(self, project_path):
        self.project_path = Path(project_path)
        self.assets_dir = self.project_path / 'assets'
        
    def add_image(self, source_path, dest_name=None):
        """Add image to project assets."""
        source = Path(source_path)
        if not dest_name:
            dest_name = source.name
            
        dest_path = self.assets_dir / 'images' / dest_name
        dest_path.parent.mkdir(parents=True, exist_ok=True)
        
        shutil.copy2(source, dest_path)
        return f"assets/images/{dest_name}"
        
    def add_icon(self, source_path, dest_name=None):
        """Add icon to project assets."""
        source = Path(source_path)
        if not dest_name:
            dest_name = source.name
            
        dest_path = self.assets_dir / 'icons' / dest_name
        dest_path.parent.mkdir(parents=True, exist_ok=True)
        
        shutil.copy2(source, dest_path)
        return f"assets/icons/{dest_name}"

if __name__ == "__main__":
    import sys
    if len(sys.argv) < 3:
        print("Usage: python asset_api.py <project_path> <asset_path>")
        sys.exit(1)
        
    api = AssetAPI(sys.argv[1])
    result = api.add_image(sys.argv[2])
    print(f"Added asset: {result}")
'''
    
    # Style Guide Engine
    style_engine = '''#!/usr/bin/env python3
"""Style Guide Engine - Convert brand guidelines to CSS variables."""
import json
import sys
from pathlib import Path

class StyleGuideEngine:
    def __init__(self, project_path):
        self.project_path = Path(project_path)
        
    def generate_css_variables(self, brand_config):
        """Generate CSS variables from brand configuration."""
        css = ":root {\\n"
        
        # Typography variables
        if "typography" in brand_config:
            typo = brand_config["typography"]
            css += f"  --font-primary: '{typo.get('primary', 'Inter')}'\\n"
            css += f"  --font-secondary: '{typo.get('secondary', 'system-ui')}'\\n"
            
            if "heading_sizes" in typo:
                for i, size in enumerate(typo["heading_sizes"]):
                    css += f"  --heading-size-{i+1}: {size}\\n"
                    
            css += f"  --body-size: {typo.get('body_size', '1rem')}\\n"
        
        # Color variables  
        if "colors" in brand_config:
            for name, value in brand_config["colors"].items():
                css += f"  --color-{name}: {value}\\n"
                
        # Layout variables
        if "layout" in brand_config:
            layout = brand_config["layout"]
            css += f"  --spacing-unit: {layout.get('spacing_unit', '8px')}\\n"
            css += f"  --max-width: {layout.get('max_width', '1200px')}\\n"
            if "border_radius" in layout:
                css += f"  --border-radius: {layout['border_radius']}\\n"
        
        css += "}\\n"
        return css
        
    def generate_from_file(self, config_path, output_path):
        """Generate CSS from brand config file."""
        with open(config_path) as f:
            brand_config = json.load(f)
            
        css = self.generate_css_variables(brand_config)
        
        with open(output_path, 'w') as f:
            f.write(css)

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Usage: python style_engine.py <project_path> <config_file> <output_file>")
        sys.exit(1)
        
    engine = StyleGuideEngine(sys.argv[1])
    engine.generate_from_file(sys.argv[2], sys.argv[3])
    print(f"Generated CSS variables: {sys.argv[3]}")
'''
    
    # Write scripts
    scripts = {
        'scripts/apis/content_api.py': content_api,
        'scripts/apis/asset_api.py': asset_api,
        'scripts/engines/style_engine.py': style_engine
    }
    
    for path, content in scripts.items():
        script_path = project_path / path
        with open(script_path, 'w') as f:
            f.write(content)
        os.chmod(script_path, 0o755)

def create_html_generator(project_path):
    """Create the HTML generation engine."""
    
    generator = '''#!/usr/bin/env python3
"""HTML Generation Engine - Create slideshow from content + styles."""
import json
import sys
from pathlib import Path

class HTMLGenerator:
    def __init__(self, project_path):
        self.project_path = Path(project_path)
        
    def generate_html(self, content_file, styles_dir, output_dir):
        """Generate complete HTML slideshow."""
        
        # Load content
        with open(content_file) as f:
            content = json.load(f)
            
        # Build HTML
        html = self._build_html_structure(content, styles_dir)
        
        # Write output
        output_path = Path(output_dir) / 'index.html'
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(output_path, 'w') as f:
            f.write(html)
            
        print(f"Generated slideshow: {output_path}")
        
    def _build_html_structure(self, content, styles_dir):
        """Build the complete HTML structure."""
        
        metadata = content.get("metadata", {})
        slides = content.get("slides", [])
        
        html = f'''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{metadata.get("title", "Slideshow")}</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="slideshow-container">
'''
        
        # Generate slides
        for slide in slides:
            html += self._generate_slide_html(slide)
            
        html += '''
    </div>
    <div class="navigation">
        <button id="prev">Previous</button>
        <button id="next">Next</button>
    </div>
    <script src="slideshow.js"></script>
</body>
</html>'''
        
        return html
        
    def _generate_slide_html(self, slide):
        """Generate HTML for a single slide."""
        slide_type = slide.get("type", "content")
        content = slide.get("content", {})
        layout = slide.get("layout", {})
        
        html = f'    <div class="slide slide-{slide_type}" id="{slide.get("id", "")}">'
        
        if slide_type == "title":
            html += f'''
        <div class="title-content">
            <h1 class="headline">{content.get("headline", "")}</h1>
            <p class="subline">{content.get("subline", "")}</p>
        </div>'''
        elif slide_type == "content":
            html += f'''
        <div class="content-slide">
            <h2 class="headline">{content.get("headline", "")}</h2>
            <div class="body">{content.get("body", "")}</div>'''
            
            if "bullets" in content:
                html += '            <ul class="bullets">'
                for bullet in content["bullets"]:
                    html += f'                <li>{bullet}</li>'
                html += '            </ul>'
            html += '        </div>'
            
        elif slide_type == "image":
            html += f'''
        <div class="image-slide">
            <h2 class="headline">{content.get("headline", "")}</h2>
            <img src="{content.get("image", "")}" alt="{content.get("caption", "")}">
            <p class="caption">{content.get("caption", "")}</p>
        </div>'''
        
        html += '    </div>\\n'
        return html

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Usage: python html_generator.py <project_path> <content_file> <output_dir>")
        sys.exit(1)
        
    generator = HTMLGenerator(sys.argv[1])
    content_file = sys.argv[2]
    output_dir = sys.argv[3]
    styles_dir = Path(sys.argv[1]) / "styles"
    
    generator.generate_html(content_file, styles_dir, output_dir)
'''
    
    script_path = project_path / 'scripts/generators/html_generator.py'
    with open(script_path, 'w') as f:
        f.write(generator)
    os.chmod(script_path, 0o755)

def main():
    parser = argparse.ArgumentParser(description='Initialize a new slideshow project')
    parser.add_argument('project_name', help='Name of the project')
    parser.add_argument('--brand', choices=['ce', 'phat', 'custom'], 
                       default='custom', help='Brand preset to use')
    parser.add_argument('--path', default='.', help='Base path for project creation')
    
    args = parser.parse_args()
    
    # Create project directory
    project_path = Path(args.path) / args.project_name
    project_path.mkdir(exist_ok=True)
    
    print(f"Creating slideshow project: {project_path}")
    
    # Build project structure
    create_directory_structure(project_path)
    create_content_api(project_path)
    create_brand_presets(project_path, args.brand)
    create_core_scripts(project_path)
    create_html_generator(project_path)
    
    print(f"✓ Project created: {project_path}")
    print(f"✓ Brand preset: {args.brand}")
    print(f"Next steps:")
    print(f"  1. cd {project_path}")
    print(f"  2. Edit content/content.json")
    print(f"  3. Add assets with: python scripts/apis/asset_api.py")
    print(f"  4. Generate: python scripts/generators/html_generator.py . content/content.json dist/")

if __name__ == "__main__":
    main()