from flask import Flask, render_template, send_from_directory, redirect, url_for
import os
import markdown

app = Flask(__name__)

FIRMWARE_DIR = os.path.join(os.path.dirname(__file__), 'firmware')
DOCS_DIR = os.path.join(os.path.dirname(__file__), 'docs')

class FirmwareRelease:
    def __init__(self, version, date, filename, changelog, size, features=None):
        self.version = version
        self.date = date
        self.filename = filename
        self.changelog = changelog
        self.size = size
        self.features = features or []

RELEASES = [
    FirmwareRelease(
        version="v1.0-beta",
        date="2026-04-16",
        filename="firmware.packed.bin",
        changelog="- Initial beta release\n- FM radio support\n- Spectrum analyzer\n- Wide Rx band\n- RSSI bar display\n- POCSAG decoder",
        size="48 KB",
        features=["FM Radio", "Spectrum", "Wide Rx", "RSSI Bar", "POCSAG"]
    ),
]

DOCS_PAGES = {
    'index': 'Главная',
    'installation': 'Установка',
    'user_guide': 'Руководство пользователя',
    'changelog': 'История изменений',
    'faq': 'FAQ',
}

def load_doc(filename):
    doc_path = os.path.join(DOCS_DIR, f'{filename}.md')
    if os.path.exists(doc_path):
        with open(doc_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return markdown.markdown(content, extensions=['fenced_code', 'tables'])
    return None

@app.route('/')
def index():
    return render_template('index.html', latest=RELEASES[0], releases=RELEASES)

@app.route('/download/')
@app.route('/downloads/')
def downloads():
    return render_template('downloads.html', releases=RELEASES)

@app.route('/download/<path:filename>')
def download(filename):
    return send_from_directory(FIRMWARE_DIR, filename, as_attachment=True)

@app.route('/docs/')
def docs():
    return render_template('docs_list.html', pages=DOCS_PAGES)

@app.route('/docs/<page>/')
def doc_page(page):
    if page not in DOCS_PAGES:
        return redirect(url_for('docs'))
    
    content = load_doc(page)
    if content is None:
        content = f"# {DOCS_PAGES[page]}\n\nСтраница в разработке."
    
    return render_template('doc_page.html', title=DOCS_PAGES[page], content=content, pages=DOCS_PAGES)

@app.route('/info/')
def info():
    return render_template('info.html')

@app.route('/flasher/')
def flasher():
    return render_template('flasher.html')

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