"""
app.py — Shiba Meals FSSS v6
Thin application assembler: creates Flask app, imports all route modules, starts server.

Module layout:
  db.py         — Flask app, config, DB helpers, CSRF, rate-limit, password, validation
  auth.py       — login_required, role_required, _user_has_role, is_manager
  models.py     — init_db() schema, seed_db() fixtures
  services.py   — Business logic: get_cash_position, get_outlet_low_stock, _build_reconciliation
  routes/
    core.py       — index, login, logout, dashboard
    production.py — production targets, records, requisitions, recipes
    store.py      — store (storekeeper) + logistics
    cashier.py    — cashier POS, cash events, wastage, outlet assignments
    finance.py    — finance dashboard, expenses, M-Pesa
    admin.py      — products, ingredients, users, outlets, roles, categories
    reports.py    — reports, analytics, settings, orders, storekeeper, waiter,
                    reconciliation, profit engine, dispatch history, activity logs

Run:  python app.py
Prod: gunicorn -c gunicorn.conf.py passenger_wsgi:application
"""
import sys, traceback
from db import app, q, run, _get_csrf_token  # noqa: F401
from models import init_db, seed_db
from flask import session, request, jsonify, render_template

# ── Register all route modules (order matters for overlapping URL rules) ──────
import routes.core        # noqa: F401
import routes.production  # noqa: F401
import routes.store       # noqa: F401
import routes.cashier     # noqa: F401
import routes.finance     # noqa: F401
import routes.admin       # noqa: F401
import routes.reports     # noqa: F401

# ── Error handlers ─────────────────────────────────────────────────────────
@app.errorhandler(404)
def not_found(e):
    if request.path.startswith('/api/'):
        return jsonify({'error': 'Not found'}), 404
    return render_template('errors/404.html'), 404

@app.errorhandler(403)
def forbidden(e):
    if request.path.startswith('/api/'):
        return jsonify({'error': 'Forbidden'}), 403
    return render_template('errors/403.html'), 403

@app.errorhandler(500)
def server_error(e):
    traceback.print_exc(file=sys.stderr)
    if request.path.startswith('/api/'):
        return jsonify({'error': 'Internal server error'}), 500
    return render_template('errors/500.html'), 500

# ── Template context: expose CSRF token to all templates ─────────────────────
@app.context_processor
def inject_csrf():
    return {'csrf_token': _get_csrf_token() if 'user_id' in session else ''}

# ── Startup ───────────────────────────────────────────────────────────────────
with app.app_context():
    init_db()
    seed_db()

if __name__ == '__main__':
    # Never run with debug=True in production
    app.run(debug=False, host='127.0.0.1', port=5000)
