"""Minimal Flask + SQLite sample for iVistaar demos."""
from __future__ import annotations

import sqlite3
from pathlib import Path

from flask import Flask, g, render_template_string

app = Flask(__name__)
DB_PATH = Path(__file__).resolve().parent / "hello.db"

PAGE = """
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello iVistaar</title>
  <style>
    body { font-family: Georgia, serif; max-width: 40rem; margin: 3rem auto; padding: 0 1rem;
           background: #f7f3ea; color: #1c1a16; }
    h1 { font-size: 2rem; margin-bottom: 0.25rem; }
    .muted { color: #666; }
    .count { font-size: 3rem; font-weight: bold; }
  </style>
</head>
<body>
  <h1>Hello from iVistaar</h1>
  <p class="muted">This Flask + SQLite sample was published by iVistaar.</p>
  <p class="count">{{ visits }}</p>
  <p>page visits recorded in SQLite.</p>
</body>
</html>
"""


def get_db() -> sqlite3.Connection:
    if "db" not in g:
        g.db = sqlite3.connect(DB_PATH)
        g.db.execute(
            "CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT DEFAULT CURRENT_TIMESTAMP)"
        )
        g.db.commit()
    return g.db


@app.teardown_appcontext
def close_db(_exc=None):
    db = g.pop("db", None)
    if db is not None:
        db.close()


@app.get("/")
def index():
    db = get_db()
    db.execute("INSERT INTO visits DEFAULT VALUES")
    db.commit()
    visits = db.execute("SELECT COUNT(*) FROM visits").fetchone()[0]
    return render_template_string(PAGE, visits=visits)


if __name__ == "__main__":
    app.run(debug=True, port=5055)
