from flask import Flask, render_template, request, jsonify
from pricing_engine import (
    compute_quote, LAYERS, ALL_QTYS, SURFACE_FINISHES, COLOURS,
    THICKNESS_OPTIONS, COPPER_OPTIONS, WORKING_DAYS_OPTIONS, COLOUR_OPTIONS,
)

app = Flask(__name__)

LAYER_LABELS = {
    "1": "1", "2": "2", "4": "4",
    "6": "6", "8": "8", "10": "10",
    "MC": "Metal Core",
}


@app.route("/")
def index():
    return render_template(
        "index.html",
        layers=[{"value": l, "label": LAYER_LABELS.get(l, l)} for l in LAYERS],
        qtys=[int(q) for q in ALL_QTYS],
        surfaces=SURFACE_FINISHES,
        colours=COLOURS,
    )


@app.route("/api/options")
def api_options():
    """Dependent option lists (thickness / copper / working days / colour) for a layer."""
    layer = str(request.args.get("layer", ""))
    colours = []
    for name in COLOURS:
        info = COLOUR_OPTIONS.get(layer, {}).get(name)
        colours.append({
            "name": name,
            "whole_qty": info["whole_qty"] if info else 0,
            "inc_amt": info["inc_amt"] if info else 0,
        })
    return jsonify({
        "thickness": [{"value": v, "add_amt": a} for v, a in THICKNESS_OPTIONS.get(layer, [])],
        "copper": [{"value": v, "add_amt": a} for v, a in COPPER_OPTIONS.get(layer, [])],
        "working_days": [{"value": v, "add_pct": p} for v, p in WORKING_DAYS_OPTIONS.get(layer, [])],
        "colours": colours,
    })


@app.route("/api/get_price", methods=["POST"])
def api_get_price():
    """Mirrors get_price.php, extended with the thickness/copper/colour/
    working-day add-ons shown in the full calculator UI."""
    data = request.get_json(force=True) or {}
    try:
        length = float(data.get("length", 0))   # mm
        width = float(data.get("width", 0))     # mm
        qty = float(data.get("qty", 0))
        layer = str(data.get("layer", ""))
        surface = data.get("surface", "")
        thickness = float(data["thickness"]) if data.get("thickness") not in (None, "") else None
        copper = float(data["copper"]) if data.get("copper") not in (None, "") else None
        colour = data.get("colour", "Green")
        working_days = int(data["working_days"]) if data.get("working_days") not in (None, "") else None
    except (TypeError, ValueError):
        return jsonify({"error": "Invalid input"}), 400

    if not layer or qty <= 0 or length <= 0 or width <= 0:
        return jsonify({"error": "length, width, qty and layer are required"}), 400

    size_sqmm = length * width
    quote = compute_quote(size_sqmm, qty, layer, surface,
                           thickness=thickness, copper=copper,
                           colour=colour, working_days=working_days)
    if quote is None:
        return jsonify({"error": "No price configured for this layer/qty/size combination"}), 404
    if "error" in quote:
        return jsonify({"error": quote["error"]}), 400

    quote["area_sqmm"] = size_sqmm
    quote["area_sqcm"] = round(size_sqmm / 100.0, 2)
    quote["total_sqmtr"] = round((size_sqmm / 1_000_000.0) * qty, 4)
    return jsonify(quote)


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