#!/usr/bin/env python3
"""
Simple web interface for Tailwind Site Rebuilder
"""

import os
import json
import subprocess
from flask import Flask, render_template_string, request, redirect, url_for, flash, send_from_directory

app = Flask(__name__)
app.secret_key = "tailwind_rebuilder_secret_key"  # For flash messages

# Base directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# HTML template embedded in the app for simplicity
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tailwind Site Rebuilder</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f7fafc;
        }
        header {
            background-color: #2b6cb0;
            color: white;
            padding: 1rem;
            margin-bottom: 2rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        h1 {
            margin: 0;
            font-size: 1.8rem;
        }
        h2 {
            color: #2b6cb0;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 0.5rem;
            margin-top: 2rem;
        }
        form {
            background-color: white;
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
            margin-bottom: 2rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        input[type="text"] {
            width: 100%;
            padding: 0.5rem;
            margin-bottom: 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 0.25rem;
            font-size: 1rem;
        }
        button {
            background-color: #2b6cb0;
            color: white;
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 0.25rem;
            cursor: pointer;
            font-size: 1rem;
        }
        button:hover {
            background-color: #2c5282;
        }
        .flash {
            padding: 1rem;
            background-color: #4fd1c5;
            color: white;
            border-radius: 0.25rem;
            margin-bottom: 1rem;
        }
        .error {
            background-color: #f56565;
        }
        .screenshot {
            max-width: 100%;
            height: auto;
            margin-top: 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 0.25rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
        }
        .analysis-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .screenshot-container {
            flex: 1;
            min-width: 300px;
        }
        .data-container {
            flex: 2;
            min-width: 300px;
        }
        pre {
            background-color: #f8f8f8;
            padding: 1rem;
            border-radius: 0.25rem;
            overflow-x: auto;
            font-size: 0.875rem;
        }
        .json-key {
            color: #2b6cb0;
        }
        .json-string {
            color: #38a169;
        }
        .json-number {
            color: #d69e2e;
        }
        .json-boolean {
            color: #d53f8c;
        }
        .json-null {
            color: #a0aec0;
        }
        .tab-container {
            margin-bottom: 2rem;
        }
        .tab-buttons {
            display: flex;
            border-bottom: 1px solid #e2e8f0;
            margin-bottom: 1rem;
        }
        .tab-button {
            padding: 0.5rem 1rem;
            background-color: transparent;
            color: #4a5568;
            border: none;
            border-bottom: 2px solid transparent;
            cursor: pointer;
            margin-right: 1rem;
        }
        .tab-button.active {
            color: #2b6cb0;
            border-bottom: 2px solid #2b6cb0;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .section-container {
            background-color: white;
            padding: 1rem;
            border-radius: 0.25rem;
            margin-bottom: 1rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
        }
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }
        .section-content {
            margin-top: 1rem;
            display: none;
        }
        .section-content.open {
            display: block;
        }
        .expand-icon {
            font-size: 1.25rem;
        }
        .ai-comment {
            background-color: #ebf8ff;
            padding: 0.75rem;
            border-left: 4px solid #4299e1;
            margin-top: 0.5rem;
            border-radius: 0.25rem;
        }
        /* Loading overlay */
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            color: white;
        }
        .loading-spinner {
            border: 5px solid #f3f3f3;
            border-top: 5px solid #2b6cb0;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 2s linear infinite;
            margin-bottom: 20px;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .flash.error {
            background-color: #f56565;
        }
        .prompt-textarea {
            width: 100%;
            min-height: 200px;
            font-family: monospace;
            padding: 12px;
            border: 1px solid #e2e8f0;
            border-radius: 0.25rem;
            margin-bottom: 1rem;
            background-color: #f8fafc;
        }
        .copy-btn {
            background-color: #4a5568;
            margin-bottom: 1rem;
        }
        .copy-btn:hover {
            background-color: #2d3748;
        }
        .prompt-container {
            margin-bottom: 2rem;
        }
        .customize-prompt {
            margin-top: 1rem;
            padding: 1rem;
            background-color: #fff;
            border-radius: 0.25rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
        }
        .focus-area-selector {
            margin-bottom: 1rem;
        }
        .focus-area-selector label {
            margin-right: 1rem;
            font-weight: normal;
            display: inline-flex;
            align-items: center;
        }
        .focus-area-selector input {
            margin-right: 0.5rem;
        }
    </style>
</head>
<body>
    <!-- Loading overlay -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p>Analyzing website... This may take a few moments.</p>
    </div>

    <header>
        <h1>Tailwind Site Rebuilder</h1>
    </header>
    
    {% for message in get_flashed_messages(with_categories=true) %}
        <div class="flash {% if message[0] == 'error' %}error{% endif %}">{{ message[1] }}</div>
    {% endfor %}
    
    <form id="analyzeForm" method="POST" action="{{ url_for('analyze') }}">
        <label for="url">Website URL to Analyze:</label>
        <input type="text" id="url" name="url" placeholder="https://example.com" required>
        <label for="use_ai">
            <input type="checkbox" id="use_ai" name="use_ai" checked> Use AI Verification
        </label>
        <button type="submit">Analyze Website</button>
    </form>
    
    {% if rebuild_context %}
    <div class="analysis-container">
        <div class="screenshot-container">
            <h2>Screenshot</h2>
            {% if screenshot_path %}
                <img src="{{ url_for('serve_screenshot', filename=screenshot_filename) }}" alt="Website Screenshot" class="screenshot">
            {% else %}
                <p>No screenshot available</p>
            {% endif %}
        </div>
        
        <div class="data-container">
            <h2>Analysis Results</h2>
            
            <div class="tab-container">
                <div class="tab-buttons">
                    <button class="tab-button active" onclick="openTab(event, 'overview')">Overview</button>
                    <button class="tab-button" onclick="openTab(event, 'sections')">Sections</button>
                    <button class="tab-button" onclick="openTab(event, 'design')">Design</button>
                    <button class="tab-button" onclick="openTab(event, 'ai')">AI Insights</button>
                    <button class="tab-button" onclick="openTab(event, 'prompts')">Rebuild Prompts</button>
                </div>
                
                <div id="overview" class="tab-content active">
                    <h3>Site Information</h3>
                    <div class="section-container">
                        <p><strong>Title:</strong> {{ rebuild_context.site_info.title }}</p>
                        <p><strong>Domain:</strong> {{ rebuild_context.site_info.domain }}</p>
                        <p><strong>URL:</strong> {{ rebuild_context.site_info.url }}</p>
                        <p><strong>Analyzed:</strong> {{ rebuild_context.site_info.analyzed_at }}</p>
                        {% if rebuild_context.site_info.layout_patterns %}
                            <p><strong>Layout Patterns:</strong></p>
                            <ul>
                                {% for key, value in rebuild_context.site_info.layout_patterns.items() %}
                                    <li>{{ key }}: {{ value }}</li>
                                {% endfor %}
                            </ul>
                        {% endif %}
                    </div>
                    
                    <h3>Tailwind Rebuild Notes</h3>
                    <div class="section-container">
                        <p><strong>General:</strong> {{ rebuild_context.tailwind_rebuild_notes.general }}</p>
                        <p><strong>Layout:</strong> {{ rebuild_context.tailwind_rebuild_notes.layout }}</p>
                        
                        <p><strong>Components:</strong></p>
                        <ul>
                            {% for key, value in rebuild_context.tailwind_rebuild_notes.components.items() %}
                                <li><strong>{{ key }}:</strong> {{ value }}</li>
                            {% endfor %}
                        </ul>
                        
                        <p><strong>Responsive Breakpoints:</strong></p>
                        <ul>
                            {% for key, value in rebuild_context.tailwind_rebuild_notes.responsive_breakpoints.items() %}
                                <li><strong>{{ key }}:</strong> {{ value }}</li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>
                
                <div id="sections" class="tab-content">
                    <h3>Page Sections</h3>
                    {% for section in rebuild_context.layout.sections %}
                        <div class="section-container">
                            <div class="section-header" onclick="toggleSection('section-{{ loop.index }}')">
                                <h4>{{ section.type|capitalize }} Section</h4>
                                <span class="expand-icon">+</span>
                            </div>
                            <div id="section-{{ loop.index }}" class="section-content">
                                <p><strong>Content Preview:</strong> {{ section.content_preview }}</p>
                                {% if section.pattern %}
                                    <p><strong>Pattern:</strong> {{ section.pattern }}</p>
                                {% endif %}
                                <p><strong>Tailwind Notes:</strong> {{ section.tailwind_notes }}</p>
                                
                                {% if section.ai_comment %}
                                    <div class="ai-comment">
                                        <h5>AI Analysis</h5>
                                        <p><strong>Location:</strong> {{ section.ai_comment.location }}</p>
                                        <p><strong>Style:</strong> {{ section.ai_comment.style }}</p>
                                        <p><strong>Implementation:</strong> {{ section.ai_comment.implementation }}</p>
                                        {% if section.ai_comment.logo %}
                                            <p><strong>Logo Analysis:</strong> {{ section.ai_comment.logo }}</p>
                                        {% endif %}
                                    </div>
                                {% endif %}
                                
                                {% if section.logo %}
                                    <div class="ai-comment">
                                        <h5>Logo Details</h5>
                                        <p><strong>Position:</strong> {{ section.logo.position }}</p>
                                        <p><strong>Dimensions:</strong> {{ section.logo.dimensions.width }}x{{ section.logo.dimensions.height }}</p>
                                        {% if section.logo.src %}
                                            <p><strong>Source:</strong> {{ section.logo.src }}</p>
                                        {% endif %}
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                    {% endfor %}
                </div>
                
                <div id="design" class="tab-content">
                    <h3>Colors</h3>
                    <div class="section-container">
                        <p><strong>Background Colors:</strong></p>
                        <ul>
                            {% for color in rebuild_context.design.colors.background %}
                                <li>
                                    <span style="display: inline-block; width: 20px; height: 20px; background-color: {{ color }}; border: 1px solid #ddd; vertical-align: middle;"></span>
                                    {{ color }}
                                </li>
                            {% endfor %}
                        </ul>
                        
                        <p><strong>Text Colors:</strong></p>
                        <ul>
                            {% for color in rebuild_context.design.colors.text %}
                                <li>
                                    <span style="display: inline-block; width: 20px; height: 20px; background-color: {{ color }}; border: 1px solid #ddd; vertical-align: middle;"></span>
                                    {{ color }}
                                </li>
                            {% endfor %}
                        </ul>
                        
                        <p><strong>Accent Colors:</strong></p>
                        <ul>
                            {% for color in rebuild_context.design.colors.accent %}
                                <li>
                                    <span style="display: inline-block; width: 20px; height: 20px; background-color: {{ color }}; border: 1px solid #ddd; vertical-align: middle;"></span>
                                    {{ color }}
                                </li>
                            {% endfor %}
                        </ul>
                        
                        <p><strong>Suggested Tailwind Colors:</strong></p>
                        <ul>
                            {% for key, value in rebuild_context.design.colors.suggested_tailwind.items() %}
                                <li><strong>{{ key }}:</strong> {{ value }}</li>
                            {% endfor %}
                        </ul>
                    </div>
                    
                    <h3>Typography</h3>
                    <div class="section-container">
                        <p><strong>Fonts:</strong></p>
                        <ul>
                            {% for font in rebuild_context.design.typography.fonts %}
                                <li>{{ font }}</li>
                            {% endfor %}
                        </ul>
                        
                        <p><strong>Headings:</strong></p>
                        <ul>
                            {% for tag, styles in rebuild_context.design.typography.headings.items() %}
                                <li>
                                    <details>
                                        <summary><strong>{{ tag }}:</strong></summary>
                                        <ul>
                                            {% for prop, value in styles.items() %}
                                                <li>{{ prop }}: {{ value }}</li>
                                            {% endfor %}
                                        </ul>
                                    </details>
                                </li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>
                
                <div id="ai" class="tab-content">
                    {% if rebuild_context.ai_verification %}
                        <h3>AI Verification</h3>
                        <div class="section-container">
                            <p><strong>Verified at:</strong> {{ rebuild_context.ai_verification.verified_at }}</p>
                            
                            {% if rebuild_context.ai_verification.sections_analysis %}
                                <h4>Sections Analysis</h4>
                                <div class="ai-comment">{{ rebuild_context.ai_verification.sections_analysis }}</div>
                            {% endif %}
                            
                            {% if rebuild_context.ai_verification.layout_assessment %}
                                <h4>Layout Assessment</h4>
                                <div class="ai-comment">{{ rebuild_context.ai_verification.layout_assessment }}</div>
                            {% endif %}
                            
                            {% if rebuild_context.ai_verification.logo_and_branding %}
                                <h4>Logo & Branding</h4>
                                <div class="ai-comment">{{ rebuild_context.ai_verification.logo_and_branding }}</div>
                            {% endif %}
                            
                            {% if rebuild_context.ai_verification.color_analysis %}
                                <h4>Color Analysis</h4>
                                <div class="ai-comment">{{ rebuild_context.ai_verification.color_analysis }}</div>
                            {% endif %}
                            
                            {% if rebuild_context.ai_verification.responsive_strategy %}
                                <h4>Responsive Strategy</h4>
                                <div class="ai-comment">{{ rebuild_context.ai_verification.responsive_strategy }}</div>
                            {% endif %}
                            
                            {% if rebuild_context.ai_verification.tailwind_recommendations %}
                                <h4>Tailwind Recommendations</h4>
                                <div class="ai-comment">{{ rebuild_context.ai_verification.tailwind_recommendations }}</div>
                            {% endif %}
                        </div>
                    {% else %}
                        <p>No AI verification data available.</p>
                    {% endif %}
                </div>
                
                <div id="prompts" class="tab-content">
                    <h3>Tailwind Rebuild Prompts</h3>
                    <p>These prompts are engineered to help you rebuild the analyzed site using Tailwind CSS.</p>
                    
                    <div class="section-container customize-prompt">
                        <h4>Customize Prompt Focus</h4>
                        <div class="focus-area-selector">
                            <p>Select areas to emphasize in the prompt:</p>
                            <label><input type="checkbox" class="focus-option" value="layout" checked> Layout Structure</label>
                            <label><input type="checkbox" class="focus-option" value="colors" checked> Color Scheme</label>
                            <label><input type="checkbox" class="focus-option" value="typography" checked> Typography</label>
                            <label><input type="checkbox" class="focus-option" value="components" checked> Components</label>
                            <label><input type="checkbox" class="focus-option" value="responsive" checked> Responsive Design</label>
                        </div>
                        <button id="generatePromptBtn" class="copy-btn">Regenerate Prompt</button>
                    </div>
                    
                    <div class="prompt-container">
                        <h4>Complete Site Rebuild Prompt</h4>
                        <button class="copy-btn" onclick="copyToClipboard('completePrompt')">Copy to Clipboard</button>
                        <textarea id="completePrompt" class="prompt-textarea" readonly></textarea>
                    </div>
                    
                    <div class="prompt-container">
                        <h4>Component-Specific Prompts</h4>
                        
                        {% for section in rebuild_context.layout.sections %}
                            <div class="section-container">
                                <h5>{{ section.type|capitalize }} Section</h5>
                                <button class="copy-btn" onclick="copyToClipboard('sectionPrompt{{ loop.index }}')">Copy to Clipboard</button>
                                <textarea id="sectionPrompt{{ loop.index }}" class="prompt-textarea" readonly></textarea>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <h2>Raw JSON</h2>
    <pre id="json-viewer">{{ json_data }}</pre>
    {% endif %}
    
    <script>
        function openTab(evt, tabName) {
            var i, tabContent, tabButtons;
            tabContent = document.getElementsByClassName("tab-content");
            for (i = 0; i < tabContent.length; i++) {
                tabContent[i].className = tabContent[i].className.replace(" active", "");
            }
            tabButtons = document.getElementsByClassName("tab-button");
            for (i = 0; i < tabButtons.length; i++) {
                tabButtons[i].className = tabButtons[i].className.replace(" active", "");
            }
            document.getElementById(tabName).className += " active";
            evt.currentTarget.className += " active";
            
            // Generate prompts when switching to the prompts tab
            if (tabName === "prompts") {
                generatePrompts();
            }
        }
        
        function toggleSection(sectionId) {
            var section = document.getElementById(sectionId);
            if (section.className.indexOf("open") !== -1) {
                section.className = section.className.replace(" open", "");
                section.previousElementSibling.querySelector(".expand-icon").innerHTML = "+";
            } else {
                section.className += " open";
                section.previousElementSibling.querySelector(".expand-icon").innerHTML = "-";
            }
        }
        
        function copyToClipboard(elementId) {
            const element = document.getElementById(elementId);
            element.select();
            document.execCommand('copy');
            
            // Visual feedback
            const originalColor = element.style.backgroundColor;
            element.style.backgroundColor = "#c6f6d5";  // Light green
            setTimeout(() => {
                element.style.backgroundColor = originalColor;
            }, 500);
        }
        
        function generatePrompts() {
            // Get selected focus areas
            const focusAreas = Array.from(document.querySelectorAll('.focus-option:checked')).map(cb => cb.value);
            
            // Generate the complete site rebuild prompt
            const completePrompt = generateCompleteSitePrompt(focusAreas);
            document.getElementById('completePrompt').value = completePrompt;
            
            // Generate component-specific prompts
            const sections = JSON.parse(document.getElementById('json-viewer').textContent).layout.sections;
            sections.forEach((section, index) => {
                const sectionPrompt = generateSectionPrompt(section, focusAreas);
                document.getElementById(`sectionPrompt${index + 1}`).value = sectionPrompt;
            });
        }
        
        function generateCompleteSitePrompt(focusAreas) {
            const data = JSON.parse(document.getElementById('json-viewer').textContent);
            
            let prompt = `Create a Tailwind CSS implementation of a website with the following specifications:\n\n`;
            
            // Add site info
            prompt += `Site Title: ${data.site_info.title}\n`;
            prompt += `URL: ${data.site_info.url}\n\n`;
            
            // Add selected focus areas
            if (focusAreas.includes('layout')) {
                prompt += `## Layout Structure\n`;
                prompt += `Overall layout: ${data.tailwind_rebuild_notes.layout}\n`;
                prompt += `Page sections in order:\n`;
                data.layout.sections.forEach(section => {
                    prompt += `- ${section.type.toUpperCase()}: ${section.content_preview}\n  ${section.tailwind_notes}\n`;
                    if (section.ai_comment && section.ai_comment.implementation) {
                        prompt += `  Suggested classes: ${section.ai_comment.implementation}\n`;
                    }
                });
                prompt += `\n`;
            }
            
            if (focusAreas.includes('colors')) {
                prompt += `## Color Scheme\n`;
                if (data.design.colors.suggested_tailwind) {
                    prompt += `Tailwind color mapping:\n`;
                    Object.entries(data.design.colors.suggested_tailwind).forEach(([key, value]) => {
                        prompt += `- ${key}: ${value}\n`;
                    });
                } else {
                    prompt += `Background colors: ${data.design.colors.background.join(', ')}\n`;
                    prompt += `Text colors: ${data.design.colors.text.join(', ')}\n`;
                    prompt += `Accent colors: ${data.design.colors.accent.join(', ')}\n`;
                }
                prompt += `\n`;
            }
            
            if (focusAreas.includes('typography')) {
                prompt += `## Typography\n`;
                prompt += `Fonts: ${data.design.typography.fonts.join(', ')}\n`;
                prompt += `Heading styles:\n`;
                Object.entries(data.design.typography.headings).forEach(([tag, styles]) => {
                    prompt += `- ${tag}: `;
                    const styleList = Object.entries(styles).map(([prop, val]) => `${prop}: ${val}`).join(', ');
                    prompt += styleList + '\n';
                });
                prompt += `\n`;
            }
            
            if (focusAreas.includes('components')) {
                prompt += `## Components\n`;
                Object.entries(data.tailwind_rebuild_notes.components).forEach(([name, note]) => {
                    prompt += `- ${name}: ${note}\n`;
                });
                prompt += `\n`;
            }
            
            if (focusAreas.includes('responsive')) {
                prompt += `## Responsive Design\n`;
                prompt += `Strategy: ${data.tailwind_rebuild_notes.general}\n`;
                prompt += `Breakpoints:\n`;
                Object.entries(data.tailwind_rebuild_notes.responsive_breakpoints).forEach(([name, value]) => {
                    prompt += `- ${name}: ${value}\n`;
                });
                prompt += `\n`;
            }
            
            // Add AI recommendations if available
            if (data.ai_verification && data.ai_verification.tailwind_recommendations) {
                prompt += `## AI Recommendations\n`;
                prompt += `${data.ai_verification.tailwind_recommendations}\n\n`;
            }
            
            prompt += `Please provide the complete HTML structure using Tailwind CSS classes based on these specifications.`;
            
            return prompt;
        }
        
        function generateSectionPrompt(section, focusAreas) {
            let prompt = `Create a Tailwind CSS implementation for a ${section.type} section with the following specifications:\n\n`;
            
            prompt += `Content: ${section.content_preview}\n`;
            if (section.pattern) {
                prompt += `Pattern: ${section.pattern}\n`;
            }
            prompt += `Tailwind Notes: ${section.tailwind_notes}\n\n`;
            
            if (section.ai_comment) {
                if (section.ai_comment.location) {
                    prompt += `Location: ${section.ai_comment.location}\n`;
                }
                if (section.ai_comment.style) {
                    prompt += `Style: ${section.ai_comment.style}\n`;
                }
                if (section.ai_comment.implementation) {
                    prompt += `Suggested Tailwind classes: ${section.ai_comment.implementation}\n`;
                }
            }
            
            if (section.logo) {
                prompt += `\nIncludes logo:\n`;
                prompt += `- Position: ${section.logo.position}\n`;
                prompt += `- Dimensions: ${section.logo.dimensions.width}x${section.logo.dimensions.height}\n`;
                if (section.logo.src) {
                    prompt += `- Source: ${section.logo.src}\n`;
                }
            }
            
            prompt += `\nPlease provide the HTML code for this ${section.type} section using Tailwind CSS classes.`;
            
            return prompt;
        }
        
        // Add event listener to generate prompt button
        document.addEventListener('DOMContentLoaded', function() {
            const generateBtn = document.getElementById('generatePromptBtn');
            if (generateBtn) {
                generateBtn.addEventListener('click', generatePrompts);
            }
            
            // Pretty-print the JSON when page loads
            var jsonViewer = document.getElementById('json-viewer');
            if (jsonViewer) {
                var jsonText = jsonViewer.textContent;
                var jsonObj = JSON.parse(jsonText);
                var formattedJson = JSON.stringify(jsonObj, null, 2);
                // Apply syntax highlighting
                formattedJson = formattedJson
                    .replace(/"([^"]+)":/g, '<span class="json-key">"$1"</span>:')
                    .replace(/"([^"]*)"/g, '<span class="json-string">"$1"</span>')
                    .replace(/\b(\d+)\b/g, '<span class="json-number">$1</span>')
                    .replace(/\b(true|false)\b/g, '<span class="json-boolean">$1</span>')
                    .replace(/\bnull\b/g, '<span class="json-null">null</span>');
                jsonViewer.innerHTML = formattedJson;
            }
        });
        
        // Show loading overlay when form is submitted
        document.getElementById('analyzeForm').addEventListener('submit', function() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        });
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    """Home page"""
    # Check if there's a recent analysis
    output_dir = os.path.join(BASE_DIR, "output_with_ai")
    context_file = os.path.join(output_dir, "rebuild_context.json")
    
    rebuild_context = None
    screenshot_path = None
    screenshot_filename = None
    json_data = ""
    
    if os.path.exists(context_file):
        try:
            with open(context_file, 'r') as f:
                rebuild_context = json.load(f)
                json_data = json.dumps(rebuild_context)
                
            # Find the most recent screenshot
            screenshots_dir = os.path.join(output_dir, "screenshots")
            if os.path.exists(screenshots_dir):
                screenshot_files = [f for f in os.listdir(screenshots_dir) if f.endswith((".png", ".jpg", ".svg"))]
                if screenshot_files:
                    # Sort by modification time, newest first
                    screenshot_files.sort(key=lambda x: os.path.getmtime(os.path.join(screenshots_dir, x)), reverse=True)
                    screenshot_filename = screenshot_files[0]
                    screenshot_path = os.path.join(screenshots_dir, screenshot_filename)
                    app.logger.info(f"Using latest screenshot: {screenshot_filename}")
        except Exception as e:
            flash(f"Error loading previous analysis: {str(e)}", "error")
    
    return render_template_string(
        HTML_TEMPLATE, 
        rebuild_context=rebuild_context,
        screenshot_path=screenshot_path,
        screenshot_filename=screenshot_filename,
        json_data=json_data
    )

@app.route('/analyze', methods=['POST'])
def analyze():
    """Run analysis on submitted URL"""
    url = request.form.get('url')
    use_ai = 'use_ai' in request.form
    
    if not url:
        flash("Please enter a URL to analyze")
        return redirect(url_for('index'))
    
    try:
        # Prepare the command
        cmd = ["./demo-verify.sh", url]
        
        # Set environment variable for AI if needed
        env = os.environ.copy()
        if not use_ai:
            env["SKIP_AI"] = "1"
        
        # Log the command being executed
        app.logger.info(f"Executing command: {' '.join(cmd)}")
        
        # Run the analysis with real-time output capture
        process = subprocess.Popen(
            cmd, 
            stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE,
            env=env,
            text=True,
            bufsize=1
        )
        
        # Capture output
        stdout_output = []
        stderr_output = []
        
        # Read output in real-time
        for line in process.stdout:
            app.logger.info(f"STDOUT: {line.strip()}")
            stdout_output.append(line)
        
        # Read any error output
        for line in process.stderr:
            app.logger.error(f"STDERR: {line.strip()}")
            stderr_output.append(line)
            
        # Wait for process to complete
        process.wait()
        
        # Check return code
        if process.returncode != 0:
            error_msg = ''.join(stderr_output)
            flash(f"Error running analysis: {error_msg}", "error")
            app.logger.error(f"Process failed with return code {process.returncode}")
            return redirect(url_for('index'))
        
        # Log success
        stdout_str = ''.join(stdout_output)
        app.logger.info(f"Analysis completed successfully. Output: {stdout_str}")
        
        flash(f"Analysis of {url} completed successfully!", "success")
        return redirect(url_for('index'))
        
    except Exception as e:
        app.logger.exception(f"Exception during analysis: {str(e)}")
        flash(f"Error: {str(e)}", "error")
        return redirect(url_for('index'))

@app.route('/screenshots/<filename>')
def serve_screenshot(filename):
    """Serve screenshot images"""
    screenshots_dir = os.path.join(BASE_DIR, "output_with_ai", "screenshots")
    return send_from_directory(screenshots_dir, filename)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000) 