"""
Place Social Boosting orders: charge user wallet (MMK), then call provider API.
"""

from __future__ import annotations

from typing import Any

import models
from social_boosting_client import api_post_add, get_services
from social_boosting_pricing import estimate_charge_mmk, parse_min_max


def _find_service(services: list[dict[str, Any]], service_id: int) -> dict[str, Any] | None:
    for s in services:
        try:
            if int(s.get("service", -1)) == service_id:
                return s
        except (TypeError, ValueError):
            continue
    return None


def place_social_boost_order(user: dict[str, Any], data: dict[str, Any]) -> tuple[dict[str, Any], int]:
    uid = int(user["id"])
    try:
        service_id = int(data.get("service_id") or 0)
    except (TypeError, ValueError):
        return {"ok": False, "error": "Invalid service."}, 400
    if service_id < 1:
        return {"ok": False, "error": "Invalid service."}, 400

    link = (data.get("link") or "").strip()
    if not link:
        return {"ok": False, "error": "Link is required."}, 400

    svc_list = get_services()
    if isinstance(svc_list, dict):
        return {"ok": False, "error": svc_list.get("error", "Could not load services.")}, 503
    svc = _find_service(svc_list, service_id)
    if not svc:
        return {"ok": False, "error": "Service not found."}, 400

    stype = (svc.get("type") or "").strip()
    qmin, qmax = parse_min_max(svc)

    quantity = int(data.get("quantity") or 0)
    comments = (data.get("comments") or "").strip()
    username = (data.get("username") or "").strip()

    api_fields: dict[str, Any] = {"service": service_id, "link": link}
    qty_store = 0
    comments_preview = ""

    if stype == "Custom Comments":
        if not comments:
            return {"ok": False, "error": "Enter one comment per line."}, 400
        lines = [x for x in comments.replace("\r\n", "\n").split("\n") if x.strip()]
        nlines = len(lines)
        if nlines < qmin or nlines > qmax:
            return {"ok": False, "error": f"Comment lines must be between {qmin} and {qmax}."}, 400
        mmk, usd = estimate_charge_mmk(svc, comments=comments)
        api_fields["comments"] = comments
        qty_store = nlines
        comments_preview = (comments[:180] + "…") if len(comments) > 180 else comments
    elif stype == "Comment Likes":
        if quantity < qmin or quantity > qmax:
            return {"ok": False, "error": f"Quantity must be between {qmin} and {qmax}."}, 400
        if not username:
            return {"ok": False, "error": "Username (comment owner) is required for this service."}, 400
        mmk, usd = estimate_charge_mmk(svc, quantity=quantity)
        api_fields["quantity"] = quantity
        api_fields["username"] = username
        qty_store = quantity
    elif stype == "Poll":
        ans = data.get("answer_number")
        try:
            ans_i = int(ans) if ans is not None else 0
        except (TypeError, ValueError):
            ans_i = 0
        if ans_i < 1:
            return {"ok": False, "error": "Poll answer number is required."}, 400
        if quantity < qmin or quantity > qmax:
            return {"ok": False, "error": f"Quantity must be between {qmin} and {qmax}."}, 400
        mmk, usd = estimate_charge_mmk(svc, quantity=quantity)
        api_fields["quantity"] = quantity
        api_fields["answer_number"] = ans_i
        qty_store = quantity
    else:
        # Default and similar
        if quantity < qmin or quantity > qmax:
            return {"ok": False, "error": f"Quantity must be between {qmin} and {qmax}."}, 400
        mmk, usd = estimate_charge_mmk(svc, quantity=quantity)
        api_fields["quantity"] = quantity
        qty_store = quantity

    bal = models.get_balance(uid)
    if bal < mmk:
        return {
            "ok": False,
            "error": f"Insufficient wallet balance. Need {mmk:,} MMK (≈ ${usd:.4f} USD est.), have {bal:,} MMK.",
        }, 400

    models.adjust_balance(uid, -mmk)
    result = api_post_add(api_fields)

    if isinstance(result, dict) and result.get("error"):
        models.adjust_balance(uid, mmk)
        return {"ok": False, "error": str(result["error"])[:400]}, 400

    panel_oid = None
    if isinstance(result, dict) and "order" in result:
        try:
            panel_oid = int(result["order"])
        except (TypeError, ValueError):
            panel_oid = None

    prov_msg = ""
    if isinstance(result, dict):
        prov_msg = str(result)[:500]

    models.insert_social_boost_order(
        uid,
        provider_order_id=panel_oid,
        service_id=service_id,
        service_name=str(svc.get("name") or "")[:500],
        service_type=stype,
        link=link,
        quantity=qty_store,
        comments_preview=comments_preview,
        amount_mmk=mmk,
        status="submitted",
        provider_message=prov_msg,
    )

    new_bal = models.get_balance(uid)
    return {
        "ok": True,
        "message": "Order placed. Amount deducted from your wallet.",
        "provider_order_id": panel_oid,
        "amount_mmk": mmk,
        "estimated_usd": round(usd, 6),
        "balance_mmk": new_bal,
    }, 200
