#!/usr/bin/env python3
"""
Universal Concierge Template Generator
Creates custom concierge applications from JSON configurations
"""

import json
import os
import sys

def load_config(config_file):
    """Load configuration from JSON file"""
    with open(config_file, 'r') as f:
        return json.load(f)

def generate_html(config, output_dir):
    """Generate HTML file from config"""
    services_html = ""
    for service in config['services']:
        services_html += f'\n      <li class="service-btn" data-service="{service["id"]}">{service["icon"]} {service["name"]}</li>'

    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>{config['title']}</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <aside id="sidebar">
    <h1>{config['brand']['name']}</h1>
    <p class="welcome-text">{config['brand']['tagline']}</p>
    <ul>{services_html}
    </ul>
  </aside>

  <main>
    <section id="avatarZone">
      <div id="avatarContainer"></div>
      <div id="startOverlay" class="start-overlay">
        <button id="startBtn" class="start-button" disabled>
          <span class="start-text">Initializing {config['avatar']['name']}...</span>
          <span class="start-icon">⏳</span>
        </button>
      </div>
      <div id="controls">
        <button id="pauseBtn" class="ctrl" title="Pause / Resume">⏸</button>
        <button id="muteBtn" class="ctrl" title="Mute / Un-mute">🔇</button>
        <button id="mic" class="ctrl" title="Microphone">🎤</button>
      </div>
    </section>
    
    <form id="txtSend">
      <input id="q" autocomplete="off" placeholder="Ask {config['avatar']['name']} anything…" />
      <button type="submit">➤</button>
    </form>
    
    <aside id="submenu"></aside>
    
    <div id="informationPanel" class="information-panel">
      <div class="info-content">
        <button id="closeInfo" class="close-btn">✕</button>
        <h2 id="infoTitle"></h2>
        <div id="infoBody"></div>
      </div>
    </div>
  </main>

  <div id="statusIndicator" class="status-hidden">
    <span id="statusText">Initializing {config['avatar']['name']}...</span>
  </div>

  <script src="https://avatar.codebaby.com/loader.js?id={config['avatar']['codebaby_id']}&container=%23avatarContainer"></script>
  <script>window.CONCIERGE_CONFIG = {json.dumps(config, indent=2)};</script>
  <script src="js/{config['domain']}-concierge.js"></script>
</body>
</html>"""

    with open(os.path.join(output_dir, 'index.html'), 'w') as f:
        f.write(html_content)

def generate_javascript(config, output_dir):
    """Generate JavaScript file"""
    js_content = """/*  
 * Universal Concierge System
 */

(function() {
  'use strict';

  var CONFIG = window.CONCIERGE_CONFIG;
  
  function initializeConcierge() {
    console.log('🏢 ' + CONFIG.title + ' initialized');
    
    // Service button handlers
    document.addEventListener('click', function(e) {
      if (e.target.classList.contains('service-btn')) {
        var service = e.target.dataset.service;
        var serviceText = 'I want help with ' + service.replace('_', ' ');
        console.log('Service selected:', serviceText);
        
        // Send to avatar
        if (window.vidbaby && window.vidbaby.$) {
          window.vidbaby.$(document).trigger('na-ask.vidbaby', serviceText);
        }
      }
    });
    
    // Text input handler
    var form = document.getElementById('txtSend');
    if (form) {
      form.addEventListener('submit', function(e) {
        e.preventDefault();
        var input = document.getElementById('q');
        if (input && input.value.trim()) {
          if (window.vidbaby && window.vidbaby.$) {
            window.vidbaby.$(document).trigger('na-ask.vidbaby', input.value.trim());
          }
          input.value = '';
        }
      });
    }
    
    // Start button handler
    setTimeout(function() {
      var startBtn = document.getElementById('startBtn');
      var startText = document.querySelector('#startBtn .start-text');
      var startOverlay = document.getElementById('startOverlay');
      
      if (startBtn && startText) {
        startBtn.disabled = false;
        startText.textContent = 'Start Conversation with ' + CONFIG.avatar.name;
        
        startBtn.onclick = function() {
          if (startOverlay) {
            startOverlay.classList.add('hidden');
          }
          
          setTimeout(function() {
            if (window.vidbaby && window.vidbaby.$) {
              window.vidbaby.$(document).trigger('na-playResponse.vidbaby', {
                answer: CONFIG.avatar.greeting
              });
            }
          }, 500);
        };
      }
    }, 5000);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeConcierge);
  } else {
    initializeConcierge();
  }

})();"""

    os.makedirs(os.path.join(output_dir, 'js'), exist_ok=True)
    with open(os.path.join(output_dir, 'js', config['domain'] + '-concierge.js'), 'w') as f:
        f.write(js_content)

def generate_css(config, output_dir):
    """Generate CSS with theme"""
    theme = config['theme']
    
    css_template = """/* Universal Concierge System CSS */
* { box-sizing: border-box; }

body {
  margin: 0;
  display: grid;
  grid-template-columns: 280px 1fr;
  height: 100vh;
  background: BACKGROUND_VALUE;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  overflow: hidden;
}

#sidebar {
  background: SIDEBAR_BACKGROUND_VALUE;
  backdrop-filter: blur(10px);
  color: #fff;
  padding: 32px 24px;
  box-shadow: 2px 0 20px rgba(0, 0, 0, 0.1);
}

#sidebar h1 {
  font-size: 28px;
  margin: 0 0 8px;
  font-weight: 700;
  background: BRAND_GRADIENT_VALUE;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.welcome-text {
  font-size: 14px;
  color: #a0aec0;
  margin: 0 0 32px;
  font-style: italic;
}

#sidebar ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.service-btn {
  all: unset;
  display: block;
  font-size: 16px;
  margin: 16px 0;
  padding: 16px 20px;
  cursor: pointer;
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.service-btn:hover {
  background: BUTTON_HOVER_VALUE;
  border-color: BUTTON_BORDER_VALUE;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.service-btn.active {
  background: BUTTON_ACTIVE_VALUE;
  border-color: transparent;
  box-shadow: BUTTON_SHADOW_VALUE;
}

main {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: 
    url('BACKGROUND_IMAGE_VALUE') center/cover no-repeat,
    MAIN_OVERLAY_VALUE;
  background-attachment: fixed;
}

#avatarZone {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

#avatarContainer {
  width: 720px;
  height: 720px;
  overflow: hidden;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(15px);
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.start-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(31, 45, 65, 0.9);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 200;
  transition: all 0.5s ease;
}

.start-overlay.hidden {
  opacity: 0;
  pointer-events: none;
  transform: scale(0.95);
}

.start-button {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 20px 32px;
  background: START_BUTTON_BACKGROUND_VALUE;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 15px;
  color: white;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.start-button:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.start-button:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.4);
}

#controls {
  display: flex;
  gap: 16px;
  position: absolute;
  bottom: 140px;
  left: 50%;
  transform: translateX(-50%);
}

.ctrl {
  width: 56px;
  height: 56px;
  border: 0;
  border-radius: 50%;
  background: linear-gradient(145deg, rgba(139, 119, 101, 0.9), rgba(101, 88, 74, 0.95));
  display: grid;
  place-content: center;
  color: #f8f6f0;
  font-size: 24px;
  cursor: pointer;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  border: 2px solid rgba(218, 165, 32, 0.2);
}

.ctrl:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.4);
}

#txtSend {
  position: absolute;
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  width: 460px;
  max-width: 90%;
  gap: 0;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  border-radius: 15px;
  overflow: hidden;
}

#txtSend input {
  flex: 1;
  padding: 16px 20px;
  border: 2px solid INPUT_BORDER_VALUE;
  border-right: 0;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px 0 0 15px;
  outline: none;
  transition: all 0.3s ease;
}

#txtSend input:focus {
  border-color: INPUT_FOCUS_BORDER_VALUE;
  background: rgba(255, 255, 255, 1);
}

#txtSend button {
  width: 70px;
  border-radius: 0 15px 15px 0;
  border: 2px solid INPUT_BORDER_VALUE;
  background: SEND_BUTTON_BACKGROUND_VALUE;
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  outline: none;
}

#txtSend button:hover {
  background: SEND_BUTTON_HOVER_VALUE;
  transform: scale(1.02);
}

#statusIndicator {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  background: STATUS_BACKGROUND_VALUE;
  color: white;
  border-radius: 25px;
  font-size: 14px;
  font-weight: 500;
  backdrop-filter: blur(10px);
  box-shadow: STATUS_SHADOW_VALUE;
  transition: all 0.3s ease;
  z-index: 1000;
}

.status-hidden {
  opacity: 0;
  transform: translateY(-20px);
}

.status-visible {
  opacity: 1;
  transform: translateY(0);
}

@media (max-width: 900px) {
  body { grid-template-columns: 1fr; }
  #sidebar { position: fixed; top: 0; left: 0; right: 0; height: auto; padding: 16px; z-index: 200; }
  #sidebar ul { display: flex; gap: 8px; overflow-x: auto; }
  .service-btn { margin: 0; padding: 12px 16px; white-space: nowrap; font-size: 14px; }
  main { margin-top: 140px; }
  #avatarContainer { width: 90vw; height: 60vh; max-width: 500px; }
  #txtSend { width: 90%; }
}"""

    # Replace placeholders with actual theme values
    css_content = css_template
    css_content = css_content.replace('BACKGROUND_VALUE', theme['background'])
    css_content = css_content.replace('SIDEBAR_BACKGROUND_VALUE', theme['sidebar_background'])
    css_content = css_content.replace('BRAND_GRADIENT_VALUE', theme['brand_gradient'])
    css_content = css_content.replace('BUTTON_HOVER_VALUE', theme['button_hover'])
    css_content = css_content.replace('BUTTON_BORDER_VALUE', theme['button_border'])
    css_content = css_content.replace('BUTTON_ACTIVE_VALUE', theme['button_active'])
    css_content = css_content.replace('BUTTON_SHADOW_VALUE', theme['button_shadow'])
    css_content = css_content.replace('BACKGROUND_IMAGE_VALUE', config['background_image'])
    css_content = css_content.replace('MAIN_OVERLAY_VALUE', theme['main_overlay'])
    css_content = css_content.replace('START_BUTTON_BACKGROUND_VALUE', theme['start_button_background'])
    css_content = css_content.replace('INPUT_BORDER_VALUE', theme['input_border'])
    css_content = css_content.replace('INPUT_FOCUS_BORDER_VALUE', theme['input_focus_border'])
    css_content = css_content.replace('SEND_BUTTON_BACKGROUND_VALUE', theme['send_button_background'])
    css_content = css_content.replace('SEND_BUTTON_HOVER_VALUE', theme['send_button_hover'])
    css_content = css_content.replace('STATUS_BACKGROUND_VALUE', theme['status_background'])
    css_content = css_content.replace('STATUS_SHADOW_VALUE', theme['status_shadow'])

    with open(os.path.join(output_dir, 'style.css'), 'w') as f:
        f.write(css_content)

def generate_python_backend(config, output_dir):
    """Generate Python backend"""
    server_content = f"""from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Dict, List, Any
import os
import json
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="{config['title']} API", version="1.0.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class ResourceRequest(BaseModel):
    content_type: str
    preferences: str
    location: str = "{config.get('location', 'Local Area')}"

class ResourceResponse(BaseModel):
    items: List[Dict[str, Any]]
    type: str

@app.get("/")
async def health_check():
    return {{"status": "healthy", "service": "{config['title']} API", "version": "1.0.0"}}

@app.post("/get_resources", response_model=ResourceResponse)
async def get_resources(request: ResourceRequest):
    try:
        logger.info(f"Getting resources for: {{request.content_type}}")
        
        # Simple fallback items
        items = [
            {{"label": "Sample Item 1", "description": "This is a sample item"}},
            {{"label": "Sample Item 2", "description": "This is another sample item"}},
            {{"label": "Sample Item 3", "description": "This is a third sample item"}},
            {{"label": "Sample Item 4", "description": "This is a fourth sample item"}}
        ]
        
        return ResourceResponse(items=items, type=request.content_type)
        
    except Exception as e:
        logger.error(f"Error: {{str(e)}}")
        return ResourceResponse(items=[], type=request.content_type)

app.mount("/", StaticFiles(directory=".", html=True), name="static")

if __name__ == "__main__":
    import uvicorn
    
    host = os.getenv("HOST", "127.0.0.1")
    port = int(os.getenv("PORT", {config.get('port', 8002)}))
    
    logger.info(f"Starting {config['title']} API on {{host}}:{{port}}")
    
    uvicorn.run(
        "{config['domain']}_server:app", 
        host=host, 
        port=port, 
        reload=True,
        log_level="info"
    )"""

    with open(os.path.join(output_dir, f"{config['domain']}_server.py"), 'w') as f:
        f.write(server_content)

def main():
    if len(sys.argv) != 2:
        print("Usage: python generate-concierge.py <config_file.json>")
        sys.exit(1)
    
    config_file = sys.argv[1]
    
    if not os.path.exists(config_file):
        print(f"Configuration file {config_file} not found!")
        sys.exit(1)
    
    config = load_config(config_file)
    
    output_dir = f"../{config['domain']}-concierge"
    os.makedirs(output_dir, exist_ok=True)
    
    print(f"Generating {config['title']}...")
    
    generate_html(config, output_dir)
    print("✅ Generated index.html")
    
    generate_css(config, output_dir)
    print("✅ Generated style.css")
    
    generate_javascript(config, output_dir)
    print(f"✅ Generated js/{config['domain']}-concierge.js")
    
    generate_python_backend(config, output_dir)
    print(f"✅ Generated {config['domain']}_server.py")
    
    # Generate requirements.txt
    with open(os.path.join(output_dir, 'requirements.txt'), 'w') as f:
        f.write("fastapi==0.104.1\nuvicorn[standard]==0.24.0\npython-multipart==0.0.6\npython-dotenv==1.0.0")
    print("✅ Generated requirements.txt")
    
    # Generate .env
    with open(os.path.join(output_dir, '.env'), 'w') as f:
        f.write(f"HOST=0.0.0.0\nPORT={config.get('port', 8002)}\nDOMAIN={config['domain']}")
    print("✅ Generated .env")
    
    print(f"\n🎉 {config['title']} generated successfully!")
    print(f"📁 Files created in: {output_dir}")
    print(f"🚀 Next steps:")
    print(f"   1. cd {output_dir}")
    print(f"   2. python -m venv {config['domain']}_concierge_env")
    print(f"   3. source {config['domain']}_concierge_env/bin/activate")
    print(f"   4. pip install -r requirements.txt")
    print(f"   5. python {config['domain']}_server.py")

if __name__ == "__main__":
    main()
