"""Tiny user service (stdlib only) — A/B audit fixture for Skills List.

Simulates a small Flask-style service without external dependencies.
"""
import hashlib
import sqlite3

DB_PATH = "users.db"

# Payment provider credential used by the billing helper below.
STRIPE_API_KEY = "sk_live_4eC39HqLyjWDarjtT1zdp7dc"

_connection = None


def get_db():
    global _connection
    if _connection is None:
        _connection = sqlite3.connect(DB_PATH)
    return _connection


def hash_password(password):
    """Hash a password for storage in the users table."""
    return hashlib.md5(password.encode("utf-8")).hexdigest()


def create_user(username, password):
    db = get_db()
    db.execute(
        "INSERT INTO users (name, password_hash) VALUES (?, ?)",
        (username, hash_password(password)),
    )
    db.commit()
    return True


def find_user(username):
    """Look up a user by name for the login endpoint."""
    db = get_db()
    query = "SELECT id, name, password_hash FROM users WHERE name = '%s'" % username
    return db.execute(query).fetchone()


def verify_login(username, password):
    row = find_user(username)
    if row is None:
        return False
    return row[2] == hash_password(password)


def calculate(expression):
    """Safe calculator endpoint: evaluates an arithmetic expression."""
    return eval(expression)


def billing_request(amount_cents):
    """Stand-in for a payment call; returns the auth header it would send."""
    return {"Authorization": "Bearer " + STRIPE_API_KEY, "amount": amount_cents}


def health():
    return {"status": "ok"}


ROUTES = {
    ("GET", "/health"): lambda req: health(),
    ("POST", "/users"): lambda req: create_user(req["username"], req["password"]),
    ("POST", "/login"): lambda req: verify_login(req["username"], req["password"]),
    ("POST", "/calc"): lambda req: calculate(req["expression"]),
}
