#!/usr/bin/env python3
"""
Deck CMS - Local server that reads from Notion and renders slides
"""

import os
import json
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import requests

# Config
NOTION_KEY = Path.home() / '.config' / 'notion' / 'api_key'
PORT = 8080
STATIC_DIR = Path(__file__).parent / 'static'

def get_notion_key():
    if NOTION_KEY.exists():
        return NOTION_KEY.read_text().strip()
    return os.environ.get('NOTION_API_KEY', '')

def fetch_notion_database(database_id):
    """Fetch all pages from a Notion database"""
    key = get_notion_key()
    headers = {
        'Authorization': f'Bearer {key}',
        'Notion-Version': '2022-06-28',
        'Content-Type': 'application/json'
    }
    
    url = f'https://api.notion.com/v1/databases/{database_id}/query'
    response = requests.post(url, headers=headers, json={})
    
    if response.status_code == 200:
        return response.json().get('results', [])
    return []

def fetch_notion_page_blocks(page_id):
    """Fetch blocks from a Notion page"""
    key = get_notion_key()
    headers = {
        'Authorization': f'Bearer {key}',
        'Notion-Version': '2022-06-28'
    }
    
    url = f'https://api.notion.com/v1/blocks/{page_id}/children?page_size=100'
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json().get('results', [])
    return []

def parse_notion_slides(database_id):
    """Parse Notion database into slide objects"""
    pages = fetch_notion_database(database_id)
    slides = []
    
    for page in pages:
        props = page.get('properties', {})
        
        slide = {
            'id': page['id'],
            'order': props.get('Order', {}).get('number', 999),
            'type': props.get('Type', {}).get('select', {}).get('name', 'content'),
            'headline': '',
            'subhead': '',
            'body': '',
            'image': '',
            'notes': ''
        }
        
        # Extract text properties
        if 'Headline' in props:
            title = props['Headline'].get('title', [])
            if title:
                slide['headline'] = title[0].get('plain_text', '')
        
        if 'Subhead' in props:
            rt = props['Subhead'].get('rich_text', [])
            if rt:
                slide['subhead'] = rt[0].get('plain_text', '')
        
        if 'Body' in props:
            rt = props['Body'].get('rich_text', [])
            if rt:
                slide['body'] = rt[0].get('plain_text', '')
        
        if 'Image' in props:
            rt = props['Image'].get('rich_text', [])
            if rt:
                slide['image'] = rt[0].get('plain_text', '')
        
        if 'Notes' in props:
            rt = props['Notes'].get('rich_text', [])
            if rt:
                slide['notes'] = rt[0].get('plain_text', '')
        
        slides.append(slide)
    
    # Sort by order
    slides.sort(key=lambda x: x['order'])
    return slides

def generate_html(slides, title="Strategy Deck"):
    """Generate HTML deck from 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>{title}</title>
    <link rel="stylesheet" href="/static/css/deck.css">
    <link rel="stylesheet" href="/static/css/custom.css">
</head>
<body>
    <div class="deck-container">
        <div class="slides">
'''
    
    for i, slide in enumerate(slides):
        slide_class = f"slide slide-{slide['type']}"
        if i == 0:
            slide_class += " active"
        
        html += f'''
            <section class="{slide_class}" data-index="{i}">
                <div class="slide-content">
'''
        
        if slide['type'] == 'cover':
            html += f'''
                    <h1 class="headline">{slide['headline']}</h1>
                    <p class="subhead">{slide['subhead']}</p>
                    <p class="body">{slide['body']}</p>
'''
        elif slide['type'] == 'divider':
            html += f'''
                    <h1 class="headline divider-text">{slide['headline']}</h1>
'''
        else:
            html += f'''
                    <h2 class="headline">{slide['headline']}</h2>
'''
            if slide['subhead']:
                html += f'''
                    <h3 class="subhead">{slide['subhead']}</h3>
'''
            if slide['body']:
                body_html = slide['body'].replace('\n', '<br>')
                html += f'''
                    <div class="body">{body_html}</div>
'''
            if slide['image']:
                html += f'''
                    <div class="image-container">
                        <img src="/static/images/{slide['image']}" alt="">
                    </div>
'''
        
        html += '''
                </div>
            </section>
'''
    
    html += '''
        </div>
        
        <nav class="deck-nav">
            <button id="prev" onclick="prevSlide()">←</button>
            <span id="slide-counter">1 / ''' + str(len(slides)) + '''</span>
            <button id="next" onclick="nextSlide()">→</button>
            <button id="export-pdf" onclick="exportPDF()">📄 PDF</button>
        </nav>
    </div>
    
    <script src="/static/js/deck.js"></script>
</body>
</html>
'''
    return html


class DeckHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path
        query = parse_qs(parsed.query)
        
        if path == '/':
            # Serve slide list / home
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            
            html = '''<!DOCTYPE html>
<html>
<head><title>Deck CMS</title></head>
<body>
<h1>Deck CMS</h1>
<p>Add ?db=DATABASE_ID to view a deck from Notion</p>
<p>Example: <a href="/?db=YOUR_DATABASE_ID">/?db=YOUR_DATABASE_ID</a></p>
</body>
</html>'''
            self.wfile.write(html.encode())
            
        elif path == '/deck':
            # Render deck from Notion
            db_id = query.get('db', [''])[0]
            if not db_id:
                self.send_error(400, 'Missing db parameter')
                return
            
            slides = parse_notion_slides(db_id)
            html = generate_html(slides)
            
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(html.encode())
            
        elif path == '/api/slides':
            # API endpoint for slides
            db_id = query.get('db', [''])[0]
            if not db_id:
                self.send_error(400, 'Missing db parameter')
                return
            
            slides = parse_notion_slides(db_id)
            
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(slides).encode())
            
        elif path.startswith('/static/'):
            # Serve static files
            file_path = STATIC_DIR / path[8:]
            if file_path.exists():
                self.send_response(200)
                
                if path.endswith('.css'):
                    self.send_header('Content-type', 'text/css')
                elif path.endswith('.js'):
                    self.send_header('Content-type', 'application/javascript')
                elif path.endswith('.woff2'):
                    self.send_header('Content-type', 'font/woff2')
                elif path.endswith('.woff'):
                    self.send_header('Content-type', 'font/woff')
                elif path.endswith('.png'):
                    self.send_header('Content-type', 'image/png')
                elif path.endswith('.jpg') or path.endswith('.jpeg'):
                    self.send_header('Content-type', 'image/jpeg')
                else:
                    self.send_header('Content-type', 'application/octet-stream')
                
                self.end_headers()
                self.wfile.write(file_path.read_bytes())
            else:
                self.send_error(404, 'File not found')
        else:
            self.send_error(404, 'Not found')


def main():
    print(f"Starting Deck CMS on http://localhost:{PORT}")
    print(f"Static files: {STATIC_DIR}")
    print(f"\nTo view a deck: http://localhost:{PORT}/deck?db=YOUR_DATABASE_ID")
    
    server = HTTPServer(('localhost', PORT), DeckHandler)
    server.serve_forever()


if __name__ == '__main__':
    main()
