"""
Chapter 2 - Lab 2.3 backend service.
A minimal Flask app that proves the three-tier topology works
and gives the frontend something to proxy.
"""
import os
import socket
from flask import Flask, jsonify

import psycopg2
from psycopg2.extras import RealDictCursor

app = Flask(__name__)

DB_CONFIG = {
    "host": os.getenv("DB_HOST", "database"),
    "port": int(os.getenv("DB_PORT", 5432)),
    "dbname": os.getenv("DB_NAME", "labdb"),
    "user": os.getenv("DB_USER", "labuser"),
    "password": os.getenv("DB_PASSWORD", "labpass"),
}


def get_db():
    return psycopg2.connect(**DB_CONFIG, cursor_factory=RealDictCursor)


@app.route("/")
def index():
    hostname = socket.gethostname()
    return jsonify({
        "service": "ch02-backend",
        "hostname": hostname,
        "message": "Three-tier lab is running. See /health and /db.",
    })


@app.route("/health")
def health():
    return jsonify({"status": "ok", "host": socket.gethostname()})


@app.route("/db")
def db_check():
    try:
        conn = get_db()
        cur = conn.cursor()
        cur.execute("SELECT version();")
        row = cur.fetchone()
        conn.close()
        return jsonify({"db": "reachable", "version": row["version"]})
    except Exception as exc:
        return jsonify({"db": "unreachable", "error": str(exc)}), 503


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