import os
from flask import Flask, render_template_string, request
import pandas as pd

EXPORTS_DIR = "exports"
PORT = 8899

app = Flask(__name__)

TEMPLATE = """
<!DOCTYPE html>
<html data-bs-theme="dark">
<head>
    <meta charset="utf-8">
    <title>CSV Viewer</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

    <style>
        body {
            padding: 2rem;
        }
        h2, h3 {
            margin-bottom: 1rem;
        }
    </style>
</head>
<body class="bg-body text-body">

    <div class="container">
        <h2>📊 CSV Viewer</h2>

        {% if files %}
            <div class="list-group mb-4">
                {% for file in files %}
                    <a href="/view?file={{ file }}" class="list-group-item list-group-item-action {% if file == filename %}active{% endif %}">
                        {{ file }}
                    </a>
                {% endfor %}
            </div>
        {% else %}
            <p class="text-warning">Brak plików w katalogu <code>{{ dir }}</code>.</p>
        {% endif %}

        {% if table %}
            <hr>
            <h3 class="mt-4">Plik: {{ filename }}</h3>
            <div class="table-responsive">
                {{ table | safe }}
            </div>
            <script>
                $(document).ready(function() {
                    $('#csv-table').DataTable();
                });
            </script>
        {% endif %}
    </div>
</body>
</html>
"""

@app.route("/")
def index():
    files = [f for f in os.listdir(EXPORTS_DIR) if f.endswith(".csv")]
    return render_template_string(TEMPLATE, files=files, table=None, filename=None, dir=EXPORTS_DIR)

@app.route("/view")
def view_file():
    filename = request.args.get("file")
    if not filename or not filename.endswith(".csv"):
        return "Niepoprawny plik.", 400
    path = os.path.join(EXPORTS_DIR, filename)
    if not os.path.exists(path):
        return "Plik nie istnieje.", 404

    try:
        df = pd.read_csv(path)
        html_table = df.to_html(classes="table table-striped table-bordered display", index=False, table_id="csv-table")
        files = [f for f in os.listdir(EXPORTS_DIR) if f.endswith(".csv")]
        return render_template_string(TEMPLATE, files=files, table=html_table, filename=filename, dir=EXPORTS_DIR)
    except Exception as e:
        return f"Błąd odczytu CSV: {e}", 500

if __name__ == "__main__":
    os.makedirs(EXPORTS_DIR, exist_ok=True)
    app.run(host="0.0.0.0", port=PORT)