"""
api_server.py — Optional Flask bridge so the browser dashboard (or the React
entry app) can push entries to Tally with one button.

The dashboard at azizsaif.com/Murtuzabhai-tally is 100% client-side and never
needs this. Run this ONLY if you want the browser to talk to your local Tally.

Run:  python api_server.py    (listens on http://localhost:5000)
"""
from flask import Flask, request, jsonify
from flask_cors import CORS

from builder.xml_generator import build_voucher_xml
from builder.validator import validate_entries
from push.tally_importer import push_to_tally

app = Flask(__name__)
CORS(app)  # allow the browser tool to call this


@app.route("/health", methods=["GET"])
def health():
    return jsonify({"ok": True})


@app.route("/push", methods=["POST"])
def push_entries():
    data = request.get_json(force=True) or {}
    entries = data.get("entries", [])

    if not entries:
        return jsonify({"success": False, "message": "No entries"})

    problems = validate_entries(entries)
    if problems:
        return jsonify({"success": False, "message": "; ".join(problems)})

    xml_str = build_voucher_xml(entries)
    return jsonify(push_to_tally(xml_str))


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