"""Flask app that serves dashboard.html behind a session-based login form.

Used in two modes:
  - Local development: run `python web.py` and visit http://localhost:5000.
  - Production behind Cloudflare Access: this login form remains as defense-in-depth;
    edge auth (Cloudflare Access with Google SSO) is the primary gate.

Auth credentials come from .env:
  DASHBOARD_USERNAME (default: tribune)
  DASHBOARD_PASSWORD (required)
  FLASK_SECRET_KEY  (optional; auto-generated per process if not set, which logs out
                     everyone on every restart — set it in .env for stable sessions)
"""

import hmac
import os
import secrets
from datetime import timedelta
from functools import wraps
from pathlib import Path

from dotenv import load_dotenv
from flask import (
    Flask,
    abort,
    redirect,
    render_template_string,
    request,
    send_file,
    session,
    url_for,
)

load_dotenv()

DASHBOARD_PATH = Path(os.environ.get("DASHBOARD_PATH", "dashboard.html"))
USERNAME = os.environ.get("DASHBOARD_USERNAME", "tribune")
PASSWORD = os.environ.get("DASHBOARD_PASSWORD")

if not PASSWORD:
    raise SystemExit(
        "DASHBOARD_PASSWORD is not set in .env. "
        "Add a line like `DASHBOARD_PASSWORD=<a-strong-password>` and re-run."
    )

app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY") or secrets.token_hex(32)
app.permanent_session_lifetime = timedelta(days=30)


def login_required(view):
    @wraps(view)
    def wrapped(*args, **kwargs):
        if not session.get("logged_in"):
            return redirect(url_for("login", next=request.path))
        return view(*args, **kwargs)

    return wrapped


@app.route("/login", methods=["GET", "POST"])
def login():
    error = None
    if request.method == "POST":
        u = request.form.get("username", "")
        p = request.form.get("password", "")
        if hmac.compare_digest(u, USERNAME) and hmac.compare_digest(p, PASSWORD):
            session["logged_in"] = True
            session.permanent = True
            return redirect(request.args.get("next") or url_for("index"))
        error = "Invalid username or password."
    elif session.get("logged_in"):
        return redirect(url_for("index"))
    return render_template_string(LOGIN_TEMPLATE, error=error)


@app.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("login"))


@app.route("/")
@login_required
def index():
    if not DASHBOARD_PATH.exists():
        abort(
            503,
            description=(
                "dashboard.html has not been generated yet. "
                "Run `python run.py` first."
            ),
        )
    return send_file(DASHBOARD_PATH, mimetype="text/html")


@app.route("/healthz")
def healthz():
    return ("ok", 200) if DASHBOARD_PATH.exists() else ("dashboard missing", 503)


LOGIN_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign in - Funnel Tracker</title>
<style>
  body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    background: #fafafa;
    min-height: 100vh;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .card {
    background: #fff;
    padding: 32px;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    width: 100%;
    max-width: 360px;
  }
  h1 { font-size: 20px; margin: 0 0 4px; font-weight: 600; }
  .subtitle { color: #666; font-size: 13px; margin-bottom: 24px; }
  label { display: block; font-size: 12px; text-transform: uppercase; color: #666; letter-spacing: 0.5px; margin-top: 14px; margin-bottom: 4px; }
  input[type="text"], input[type="password"] {
    width: 100%;
    padding: 9px 10px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
    background: #fff;
    box-sizing: border-box;
  }
  input:focus { outline: none; border-color: #4a90e2; box-shadow: 0 0 0 2px rgba(74,144,226,0.2); }
  button {
    margin-top: 20px;
    padding: 10px;
    width: 100%;
    background: #1a1a1a;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    font-weight: 500;
  }
  button:hover { background: #333; }
  .error {
    margin-top: 14px;
    padding: 9px 12px;
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
    border-radius: 4px;
    font-size: 13px;
  }
</style>
</head>
<body>
<form class="card" method="POST" action="{{ url_for('login') }}{% if request.args.get('next') %}?next={{ request.args.get('next') }}{% endif %}">
  <h1>Funnel Tracker</h1>
  <div class="subtitle">Sign in to view the dashboard.</div>
  <label for="username">Username</label>
  <input type="text" id="username" name="username" autocomplete="username" autofocus required>
  <label for="password">Password</label>
  <input type="password" id="password" name="password" autocomplete="current-password" required>
  <button type="submit">Sign in</button>
  {% if error %}<div class="error">{{ error }}</div>{% endif %}
</form>
</body>
</html>
"""


if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host="0.0.0.0", port=port, debug=False)
