from flask import Flask, request, redirect, render_template_string, make_response, url_for
from datetime import datetime, date
from collections import defaultdict
import hashlib
import uuid
import csv
import os

app = Flask(__name__)

# ----------------- Configuration -----------------
SECRET_KEY = "KFSCIS-Secret"  # Change this for production
CSV_FILE = "participants.csv"
TXT_FILE = "participants.txt"
entries = []  # Will be loaded from file at startup


# ----------------- Token Generator -----------------
def get_today_token():
    today = date.today().isoformat()
    raw = f"{today}-{SECRET_KEY}"
    return hashlib.sha256(raw.encode()).hexdigest()[:12]


# ----------------- File Utilities -----------------
def init_files():
    """Create CSV and text files if they don't exist."""
    if not os.path.exists(CSV_FILE):
        with open(CSV_FILE, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["Date", "Time", "First Name", "Last Name", "PhD Advisor", "Fingerprint"])

    if not os.path.exists(TXT_FILE):
        with open(TXT_FILE, "w", encoding="utf-8") as f:
            f.write("Participants Log (KFSCIS Seminar Series)\n")
            f.write("=" * 60 + "\n\n")


def load_entries():
    """Load previous participants from CSV into memory at startup."""
    if not os.path.exists(CSV_FILE):
        return
    with open(CSV_FILE, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            entries.append({
                "date": row["Date"],
                "time": row["Time"],
                "firstname": row["First Name"],
                "lastname": row["Last Name"],
                "advisor": row["PhD Advisor"],
                "fingerprint": row["Fingerprint"]
            })


def append_to_files(entry):
    """Append a record to both CSV and text file."""
    # Append to CSV
    with open(CSV_FILE, "a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow([
            entry["date"],
            entry["time"],
            entry["firstname"],
            entry["lastname"],
            entry["advisor"],
            entry["fingerprint"]
        ])

    # Append to text file (human-readable)
    with open(TXT_FILE, "a", encoding="utf-8") as f:
        f.write(
            f"{entry['date']} {entry['time']} | "
            f"{entry['firstname']} {entry['lastname']} "
            f"(Advisor: {entry['advisor']}) "
            f"[Fingerprint: {entry['fingerprint']}]\n"
        )


# Initialize persistence
init_files()
load_entries()


# ----------------- Templates -----------------
form_html = """
<!doctype html>
<html>
<head>
    <title>KFSCIS Seminar Series Registration</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            height: 100vh;
            background: url('{{ url_for('static', filename='background.jpg') }}') no-repeat center center fixed;
            background-size: cover;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            color: #fff;
            text-shadow: 0px 1px 3px rgba(0,0,0,0.7);
        }
        .overlay {
            position: absolute;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.55);
            z-index: 0;
        }
        .content {
            position: relative;
            z-index: 1;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
        }
        form {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: rgba(255, 255, 255, 0.1);
            padding: 25px 30px;
            border-radius: 10px;
            box-shadow: 0 0 12px rgba(0,0,0,0.3);
            backdrop-filter: blur(5px);
            width: 320px;
        }
        input {
            width: 90%;
            padding: 10px;
            border-radius: 5px;
            border: none;
            font-size: 15px;
            outline: none;
            margin: 8px 0;
        }
        .button-row {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }
        button {
            background-color: #FF8C00;
            color: white;
            border: none;
            padding: 10px 18px;
            font-size: 16px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        button:hover { background-color: #FF7000; }
        .view-btn {
            background-color: #007BFF;
        }
        .view-btn:hover { background-color: #0066CC; }
        .error {
            color: #ff8080;
            font-weight: bold;
            margin-bottom: 10px;
        }
        h2 {
            font-size: 1.8rem;
            letter-spacing: 1px;
            margin-bottom: 20px;
        }
        footer {
            position: absolute;
            bottom: 10px;
            font-size: 0.9rem;
            color: #ddd;
        }
    </style>
</head>
<body>
    <div class="overlay"></div>
    <div class="content">
        <h2>KFSCIS Seminar Series: Technology · Research · Innovation</h2>
        {% if error %}
            <p class="error">{{ error }}</p>
        {% endif %}
        <form action="/submit/{{ token }}" method="post">
            <input type="text" name="firstname" placeholder="First Name" required>
            <input type="text" name="lastname" placeholder="Last Name" required>
            <input type="text" name="advisor" placeholder="PhD Advisor" required>
            <div class="button-row">
                <button type="submit">Register</button>
                <button type="button" class="view-btn" onclick="window.location.href='/list'">View Participants</button>
            </div>
        </form>
    </div>
    <footer>© KFSCIS 2025 · Seminar Series on Innovation</footer>
</body>
</html>
"""

list_html = """
<!doctype html>
<html>
<head>
    <title>Registered Participants - KFSCIS Seminar Series</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            background-color: #001F3F;
            min-height: 100vh;
            color: #FFFFFF;
            padding: 40px;
        }
        h2 {
            text-align: center;
            font-size: 2.2rem;
            margin-bottom: 10px;
            color: #FFFFFF;
            text-shadow: 0 2px 4px rgba(0,0,0,0.4);
        }
        .celebration {
            text-align: center;
            margin-bottom: 30px;
        }
        .celebration h3 {
            font-size: 1.6rem;
            color: #FF8C00;
            margin-bottom: 10px;
        }
        .celebration img {
            width: 320px;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(255,255,255,0.3);
        }
        .day-table {
            background: rgba(255, 255, 255, 0.08);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 40px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.3);
        }
        .day-table h3 {
            color: #FF8C00;
            text-align: center;
            margin-bottom: 10px;
            font-size: 1.5rem;
        }
        table {
            width: 100%%;
            border-collapse: collapse;
        }
        th, td {
            padding: 10px 12px;
            border-bottom: 1px solid rgba(255,255,255,0.3);
        }
        th {
            text-align: left;
            color: #FFD580;
            font-weight: bold;
        }
        tr:hover { background-color: rgba(255,255,255,0.1); }
        .back-link {
            display: inline-block;
            text-decoration: none;
            background-color: #FF8C00;
            color: white;
            padding: 10px 18px;
            border-radius: 5px;
            font-weight: bold;
            margin-top: 20px;
            transition: background-color 0.3s ease;
        }
        .back-link:hover { background-color: #FF7000; }
    </style>
</head>
<body>
    <h2>🎓 KFSCIS Seminar Series Participants 🎓</h2>
    <div class="celebration">
        <h3>🎉 Kudos to these students! 🎉</h3>
        <img src="{{ url_for('static', filename='friends.gif') }}" alt="Kudos animation">
    </div>

    {% for date, day_entries in grouped_entries.items() %}
    <div class="day-table">
        <h3>📅 Seminar Date: {{ date }}</h3>
        <table>
            <tr>
                <th>Time</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>PhD Advisor</th>
                <th>Fingerprint</th>
            </tr>
            {% for e in day_entries %}
            <tr>
                <td>{{ e.time }}</td>
                <td>{{ e.firstname }}</td>
                <td>{{ e.lastname }}</td>
                <td>{{ e.advisor }}</td>
                <td>{{ e.fingerprint }}</td>
            </tr>
            {% endfor %}
        </table>
    </div>
    {% endfor %}
    <div style="text-align:center;">
        <a href="/" class="back-link">← Back to Registration</a>
    </div>
</body>
</html>
"""

# ----------------- Routes -----------------
@app.route("/")
def root_redirect():
    token = get_today_token()
    return redirect(url_for("register_page", token=token))

@app.route("/register/<token>", methods=["GET"])
def register_page(token):
    if token != get_today_token():
        return "<h3>❌ Invalid or expired registration link.</h3>", 403
    fingerprint = request.cookies.get("fingerprint")
    if fingerprint and any(e["fingerprint"] == fingerprint for e in entries):
        return render_template_string(form_html, error="You have already registered from this device.", token=token)
    return render_template_string(form_html, error=None, token=token)

@app.route("/submit/<token>", methods=["POST"])
def submit(token):
    if token != get_today_token():
        return "<h3>❌ Invalid or expired registration link.</h3>", 403

    fingerprint = request.cookies.get("fingerprint") or str(uuid.uuid4())
    if any(e["fingerprint"] == fingerprint for e in entries):
        return render_template_string(form_html, error="You have already registered from this device.", token=token)

    firstname = request.form["firstname"].strip()
    lastname = request.form["lastname"].strip()
    advisor = request.form["advisor"].strip()
    now = datetime.now()

    entry = {
        "firstname": firstname,
        "lastname": lastname,
        "advisor": advisor,
        "date": now.strftime("%Y-%m-%d"),
        "time": now.strftime("%H:%M:%S"),
        "fingerprint": fingerprint
    }
    entries.append(entry)
    append_to_files(entry)

    resp = make_response(redirect("/list"))
    resp.set_cookie("fingerprint", fingerprint, max_age=24 * 60 * 60)
    return resp


@app.route("/list")
def show_list():
    grouped_entries = defaultdict(list)
    for e in entries:
        grouped_entries[e["date"]].append(e)
    return render_template_string(list_html, grouped_entries=grouped_entries)

# ----------------- Run -----------------
#if __name__ == "__main__":
#    app.run(debug=True, port=8000)
# Production entry point for Apache WSGI
application = app

