import os
import html
from flask import Flask, send_from_directory, abort

app = Flask(__name__)

# Configuration
CONTENT_DIR = os.path.expanduser("~/gemini/content")

def gmi_to_html(gmi_text):
    lines = gmi_text.split('\n')

    html_output = ['<!DOCTYPE html>', '<html>', '<head>',
                   '<meta charset="utf-8">',
                   '<meta name="viewport" content="width=device-width, initial-scale=1">',
                   '<style>',
                   # GLOBAL THEME:
                   # - Background: Deep Dark Grey (#131314)
                   # - Text: Soft Mint Green (#81c784)
                   # - Max-Width: 700px
                   'body{max_width:700px; margin:0 auto; padding:20px; font-family: "Courier New", monospace; line-height:1.6; background:#131314; color:#81c784;}',

                   # ASCII ART: Matches body bg, tighter line-height
                   'pre{background:#131314; color:#81c784; padding:15px; overflow-x:auto; border: 1px solid #333; border-radius:5px; white-space: pre; font-family: "Courier New", monospace; font-size: 14px; line-height: 0.7;}',

                   'img{max-width:100%; height:auto; border-radius:5px; margin: 10px 0; border: 1px solid #333;}',
                   'blockquote{border-left: 4px solid #81c784; margin: 0; padding-left: 10px; color: #a5d6a7;}',
                   'a{color: #81c784; text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 3px;} a:hover{background: #81c784; color: #131314; text-decoration: none;}',

                   # HEADERS: Now #a5d6a7 (Lighter than text, but darker than white)
                   'h1, h2, h3 {color: #a5d6a7; border-bottom: 1px solid #333; padding-bottom: 10px; margin-top: 30px;}',

                   'footer{margin-top: 50px; padding-top: 20px; border-top: 1px solid #333; font-size: 0.9em; color: #66bb6a; text-align: center;}',
                   '</style>',
                   '<title>SV1SYY Radio Mirror</title>', '</head>', '<body>']

    in_preformatted = False

    for line in lines:
        # Check for the preformatted toggle block (```)
        if line.strip().startswith("```"):
            if in_preformatted:
                html_output.append("</pre>")
            else:
                html_output.append("<pre>")
            in_preformatted = not in_preformatted
            continue

        # IF we are inside a code block, preserve EXACT spacing
        if in_preformatted:
            html_output.append(html.escape(line) + "\n")
            continue

        # IF we are in normal text, we clean it up
        line = html.escape(line.strip())

        # Handle Links and Images
        if line.startswith("=&gt;"):
            parts = line[5:].strip().split(None, 1)
            if not parts: continue
            url = parts[0]
            label = parts[1] if len(parts) > 1 else url

            if url.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
                html_output.append(f'<figure><img src="{url}" alt="{label}"><figcaption>{label}</figcaption></figure>')
            else:
                if url.endswith(".gmi"):
                    html_output.append(f'<p><a href="{url}">&#10140; {label}</a></p>')
                else:
                    html_output.append(f'<p><a href="{url}" target="_blank">&#10140; {label}</a></p>')

        elif line.startswith("#"):
            level = line.count("#", 0, 3)
            text = line.lstrip("#").strip()
            html_output.append(f'<h{level}>{text}</h{level}>')
        elif line.startswith("* "):
            html_output.append(f'<ul><li>{line[2:]}</li></ul>')
        elif line.startswith("&gt;"):
            html_output.append(f'<blockquote>{line[4:]}</blockquote>')
        elif line:
            html_output.append(f'<p>{line}</p>')

    # --- FOOTER ---
    html_output.append("""
    <footer>
        <p>📡 <strong>Gemini Mirror</strong></p>
        <p>You are viewing a read-only HTTP mirror of <a href="gemini://sv1syy.radio">gemini://sv1syy.radio</a>.</p>
        <p>The Gemini Protocol is a lightweight, privacy-focused internet protocol. 
        <a href="https://en.wikipedia.org/wiki/Gemini_(protocol)" target="_blank">Learn more on Wikipedia</a>.</p>
    </footer>
    """)

    html_output.append("</body></html>")
    return "\n".join(html_output)

@app.route('/', defaults={'path': 'index.gmi'})
@app.route('/<path:path>')
def serve_content(path):
    if ".." in path or path.startswith("/"): abort(400)
    full_path = os.path.join(CONTENT_DIR, path)
    if os.path.isdir(full_path): path = os.path.join(path, "index.gmi")

    if path.endswith(".gmi"):
        try:
            with open(os.path.join(CONTENT_DIR, path), 'r') as f:
                return gmi_to_html(f.read())
        except FileNotFoundError:
            abort(404)
    return send_from_directory(CONTENT_DIR, path)

if __name__ == '__main__':
    # HTTPS Configuration
    cert = '/home/nik/gemini/web-certs/fullchain.pem'
    key = '/home/nik/gemini/web-certs/privkey.pem'

    if os.path.exists(cert) and os.path.exists(key):
        app.run(host='0.0.0.0', port=8080, ssl_context=(cert, key))
    else:
        app.run(host='0.0.0.0', port=8080)
