#!/usr/bin/env python3
import os
import sys
import json
import time
import shutil
from pathlib import Path

def generate_static_site(readable_path, output_path, web_path):
    # Create web folder structure
    transcripts_path = web_path / "transcripts"
    data_path = web_path / "data"
    
    transcripts_path.mkdir(exist_ok=True)
    data_path.mkdir(exist_ok=True)
    
    # Get all txt files
    txt_files = sorted(readable_path.glob('*.txt'))
    
    if not txt_files:
        print("No transcript files found to generate website.")
        return 0
    
    # Create transcript pages
    transcript_list = []
    
    for txt_file in txt_files:
        name = txt_file.stem
        
        # Read text content
        try:
            with open(txt_file, 'r', encoding='utf-8') as src:
                content = src.read()
                
            # Create HTML page for this transcript
            transcript_html = f"""<!DOCTYPE html>
<html>
<head>
    <title>Transcript: {name}</title>
    <link rel="stylesheet" href="../style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div class="container">
        <header>
            <h1>Transcript: {name}</h1>
            <a href="../index.html" class="back-link">← Back to List</a>
        </header>
        <main>
            <div class="transcript-content">
                <pre>{content}</pre>
            </div>
        </main>
        <footer>
            <p>Generated on {time.strftime('%Y-%m-%d %H:%M:%S')}</p>
        </footer>
    </div>
    <script src="../script.js"></script>
</body>
</html>"""
            
            with open(transcripts_path / f"{name}.html", 'w', encoding='utf-8') as f:
                f.write(transcript_html)
            
            # Copy JSON data if available
            json_path = output_path / f"{name}.json"
            if json_path.exists():
                shutil.copy(json_path, data_path / f"{name}.json")
            
            # Add to transcript list
            transcript_list.append({
                'name': name, 
                'date': time.strftime('%Y-%m-%d'),
                'path': f"transcripts/{name}.html"
            })
            
        except Exception as e:
            print(f"Error processing {txt_file}: {str(e)}")
    
    # Create index.html
    transcripts_html = "\n".join([
        f'<li><a href="{t["path"]}">{t["name"]}</a> <span class="date">{t["date"]}</span></li>' 
        for t in transcript_list
    ])
    
    index_html = f"""<!DOCTYPE html>
<html>
<head>
    <title>Voice Transcripts</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div class="container">
        <header>
            <h1>Voice Transcripts</h1>
        </header>
        <main>
            <div class="search-container">
                <input type="text" id="searchInput" placeholder="Search transcripts...">
            </div>
            <ul class="transcript-list">
                {transcripts_html}
            </ul>
        </main>
        <footer>
            <p>Last updated: {time.strftime('%Y-%m-%d %H:%M:%S')}</p>
        </footer>
    </div>
    <script src="script.js"></script>
</body>
</html>"""
    
    with open(web_path / 'index.html', 'w', encoding='utf-8') as f:
        f.write(index_html)
    
    # Create CSS file
    css = """body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f9f9f9;
    margin: 0;
    padding: 0;
}

.container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

header {
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

h1 {
    margin-top: 0;
    color: #2c3e50;
}

.back-link {
    display: inline-block;
    margin-bottom: 20px;
    color: #3498db;
    text-decoration: none;
}

.back-link:hover {
    text-decoration: underline;
}

.transcript-list {
    list-style: none;
    padding: 0;
}

.transcript-list li {
    padding: 10px 15px;
    border-bottom: 1px solid #eee;
    transition: background-color 0.2s;
}

.transcript-list li:hover {
    background-color: #f5f5f5;
}

.transcript-list a {
    color: #3498db;
    text-decoration: none;
    font-weight: 500;
}

.transcript-list a:hover {
    text-decoration: underline;
}

.date {
    font-size: 0.8em;
    color: #7f8c8d;
    float: right;
}

pre {
    white-space: pre-wrap;
    background: #f8f8f8;
    padding: 15px;
    border-radius: 5px;
    border: 1px solid #eee;
}

.search-container {
    margin-bottom: 20px;
}

#searchInput {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 16px;
}

footer {
    margin-top: 30px;
    border-top: 1px solid #eee;
    padding-top: 10px;
    font-size: 0.9em;
    color: #7f8c8d;
}

@media (max-width: 600px) {
    .container {
        padding: 10px;
    }
}"""
    
    with open(web_path / 'style.css', 'w', encoding='utf-8') as f:
        f.write(css)
    
    # Create JavaScript file
    js = """document.addEventListener('DOMContentLoaded', function() {
    // Search functionality
    const searchInput = document.getElementById('searchInput');
    const transcriptItems = document.querySelectorAll('.transcript-list li');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            
            transcriptItems.forEach(item => {
                const text = item.textContent.toLowerCase();
                if (text.includes(searchTerm)) {
                    item.style.display = '';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    }
});"""
    
    with open(web_path / 'script.js', 'w', encoding='utf-8') as f:
        f.write(js)
    
    print(f"Static website generated in {web_path}")
    print(f"Total transcripts: {len(transcript_list)}")
    
    return len(transcript_list)

if __name__ == "__main__":
    # This allows the script to be run standalone with paths as arguments
    if len(sys.argv) != 4:
        print("Usage: python static_site_generator.py [readable_folder] [output_folder] [web_folder]")
        sys.exit(1)
    
    readable_path = Path(os.path.expanduser(sys.argv[1]))
    output_path = Path(os.path.expanduser(sys.argv[2]))
    web_path = Path(os.path.expanduser(sys.argv[3]))
    
    # Validate paths
    if not readable_path.exists():
        print(f"Error: Readable folder '{sys.argv[1]}' does not exist")
        sys.exit(1)
    if not output_path.exists():
        print(f"Error: Output folder '{sys.argv[2]}' does not exist")
        sys.exit(1)
    
    # Create web directory if it doesn't exist
    web_path.mkdir(parents=True, exist_ok=True)
    
    # Generate the site
    count = generate_static_site(readable_path, output_path, web_path)
    print(f"Generated static site with {count} transcripts") 