
import http.server
import socketserver
import os
import urllib.parse
import json
import webbrowser
import threading
import time

PORT = 8000
DIRECTORY = "site/gplus"

class GPlusCuratorHandler(http.server.SimpleHTTPRequestHandler):
    def translate_path(self, path):
        # Serve from DIRECTORY
        path = path.lstrip('/')
        return os.path.join(os.getcwd(), DIRECTORY, path)

    def do_GET(self):
        # Custom API endpoints
        if self.path == '/':
            # Find first file
            files = sorted([f for f in os.listdir(DIRECTORY) if f.endswith('.html') and f != 'index.html'])
            if files:
                self.send_response(302)
                self.send_header('Location', f'/view/{files[0]}')
                self.end_headers()
            else:
                self.send_response(200)
                self.end_headers()
                self.wfile.write(b"No HTML files found in site/gplus")
            return

        if self.path.startswith('/view/'):
            filename = self.path[6:]
            filepath = os.path.join(DIRECTORY, filename)
            
            if os.path.exists(filepath):
                # Only inject toolbar for HTML files
                if filename.lower().endswith('.html') or filename.lower().endswith('.htm'):
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    
                    with open(filepath, 'rb') as f:
                        content = f.read()
                        
                    # Inject toolbar
                    toolbar = f"""
                    <div id="curator-toolbar" style="position:fixed; top:0; left:0; right:0; background:#333; color:white; padding:10px; text-align:center; z-index:9999; display:flex; justify-content:center; gap:20px;">
                        <span style="align-self:center">{filename}</span>
                        <button onclick="keepPost()" style="background:#4CAF50; color:white; border:none; padding:10px 20px; cursor:pointer; font-size:16px;">Keep (Next)</button>
                        <button onclick="deletePost()" style="background:#f44336; color:white; border:none; padding:10px 20px; cursor:pointer; font-size:16px;">Delete</button>
                        <a href="/index.html" style="color:#aaa; align-self:center; margin-left:20px;">Index</a>
                    </div>
                    <script>
                    function keepPost() {{
                        console.log('Keeping {filename}...');
                        fetch('/api/keep?current=' + encodeURIComponent('{filename}'), {{method: 'POST'}})
                        .then(r => r.json())
                        .then(data => {{
                            console.log('Response:', data);
                            if(data.next) window.location.href = '/view/' + data.next;
                            else alert('Done! No more files.');
                        }})
                        .catch(e => {{
                            console.error('Error:', e);
                            alert('Error talking to server: ' + e);
                        }});
                    }}
                    function deletePost() {{
                        if(confirm('Delete this post?')) {{
                            console.log('Deleting {filename}...');
                            fetch('/api/delete?current=' + encodeURIComponent('{filename}'), {{method: 'POST'}})
                            .then(r => r.json())
                            .then(data => {{
                                console.log('Response:', data);
                                if(data.next) window.location.href = '/view/' + data.next;
                                else alert('Done! No more files.');
                            }})
                            .catch(e => {{
                                console.error('Error:', e);
                                alert('Error talking to server: ' + e);
                            }});
                        }}
                    }}
                    </script>
                    <div style="margin-top:60px;"></div>
                    """.encode('utf-8')
                    
                    # Insert after body
                    parts = content.split(b'<body', 1)
                    if len(parts) == 2:
                        self.wfile.write(parts[0] + b'<body' + parts[1].split(b'>', 1)[0] + b'>' + toolbar + parts[1].split(b'>', 1)[1])
                    else:
                        self.wfile.write(toolbar + content)
                    return
                else:
                    # Serve other files (css, images) cleanly
                    # Let SimpleHTTPRequestHandler handle MIME type guessing via send_head logic?
                    # But send_head uses translate_path. 
                    # If we override translate_path to handle /view/, we can redirect to super().do_GET().
                    
                    # Manual serving for simplicity here since we are inside do_GET
                    import mimetypes
                    ctype, _ = mimetypes.guess_type(filepath)
                    if ctype is None:
                        ctype = 'application/octet-stream'
                        
                    self.send_response(200)
                    self.send_header('Content-type', ctype)
                    self.end_headers()
                    with open(filepath, 'rb') as f:
                        self.wfile.write(f.read())
                    return
            else:
                self.send_error(404, "File not found")
                return

        # Default static file serving
        super().do_GET()

    def do_POST(self):
        parsed = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed.query)
        current_file = params.get('current', [''])[0]
        
        print(f"POST API: {parsed.path} current={current_file}")

        if parsed.path == '/api/keep':
            next_file = self.get_next_file(current_file)
            print(f"  -> Next: {next_file}")
            self.send_json({'next': next_file})
            
        elif parsed.path == '/api/delete':
            # Calculate next file BEFORE deleting to avoid losing position
            files = sorted([f for f in os.listdir(DIRECTORY) if f.endswith('.html') and f != 'index.html'])
            next_file = None
            try:
                # Sort reverse=True if we want newest first? output filenames start with YYYY-MM-DD.
                # Default sort is Oldest -> Newest.
                # User probably wants to go through them in some order.
                # Let's match the file system order (Oldest First) which is what 'files' is.
                cur_idx = files.index(current_file)
                if cur_idx + 1 < len(files):
                    next_file = files[cur_idx + 1]
                elif cur_idx > 0:
                    # If deleting last file, go to previous?
                    # Or stay at end?
                    # Let's just return None to indicate done/index.
                    pass
            except ValueError:
                # Current file not in list (already deleted?)
                # Fallback to first available
                if files: next_file = files[0]

            filepath = os.path.join(DIRECTORY, current_file)
            if os.path.exists(filepath):
                print(f"  -> Deleting {filepath}")
                try:
                    os.remove(filepath)
                except Exception as e:
                    print(f"  -> Error deleting: {e}")
            
            print(f"  -> Next: {next_file}")
            
            # Regenerate index
            try:
                from gplus_converter import generate_index
                generate_index(DIRECTORY)
            except Exception as e:
                print(f"  -> Error regenerating index: {e}")
                
            self.send_json({'next': next_file})

    def send_json(self, data):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode('utf-8'))

    def get_next_file(self, current):
        # Helper for 'keep' (read-only)
        files = sorted([f for f in os.listdir(DIRECTORY) if f.endswith('.html') and f != 'index.html'])
        try:
            cur_idx = files.index(current)
            if cur_idx + 1 < len(files):
                return files[cur_idx + 1]
        except ValueError:
            if files: return files[0]
        return None

def open_browser():
    time.sleep(1)
    webbrowser.open(f'http://localhost:{PORT}')

if __name__ == "__main__":
    # Ensure directory exists
    if not os.path.exists(DIRECTORY):
        print(f"Error: {DIRECTORY} does not exist.")
        exit(1)

    with socketserver.TCPServer(("", PORT), GPlusCuratorHandler) as httpd:
        print(f"Serving at http://localhost:{PORT}")
        threading.Thread(target=open_browser).start()
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass
