"""تست: پشتیبانی چند ارائه‌دهندهٔ LLM + محاسبهٔ هزینه."""

from __future__ import annotations

import sys
from pathlib import Path

APP = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(APP))

from services.llm import FREE_MODELS, PROVIDERS, LLMService, resolve_base_url  # noqa: E402

PASS, FAIL = 0, 0


def check(name: str, cond: bool, detail: object = "") -> None:
    global PASS, FAIL
    if cond:
        PASS += 1
        print(f"  ✅ {name}")
    else:
        FAIL += 1
        print(f"  ❌ {name} — {detail}")


def test_base_urls() -> None:
    print("\n۱) آدرس ارائه‌دهنده‌ها")
    for name, url in PROVIDERS.items():
        check(f"{name}: {url[:42]}", resolve_base_url(name) == url.rstrip("/"))
    check("ناشناخته → openai", resolve_base_url("whatever") == PROVIDERS["openai"])
    check("مقدار صریح اولویت دارد",
          resolve_base_url("openai", "https://mine.local/v1") == "https://mine.local/v1")
    check("آخرین / حذف می‌شود", not resolve_base_url("openai", "https://x/v1/").endswith("/"))


def test_free_models() -> None:
    print("\n۲) مدل‌های پیشنهادی")
    for provider, model in FREE_MODELS.items():
        check(f"{provider} → {model}", bool(model))
    check("همهٔ ارائه‌دهنده‌های اصلی مدل دارند", set(FREE_MODELS) <= set(PROVIDERS))


def test_client_build() -> None:
    print("\n۳) ساخت کلاینت")
    s = LLMService(api_key="gsk_test", model="llama-3.3-70b-versatile", provider="groq")
    check("available", s.available)
    check("label", s.label == "groq:llama-3.3-70b-versatile", s.label)
    check("base_url", "groq.com" in str(s._client.base_url), s._client.base_url)  # noqa: SLF001

    s2 = LLMService(api_key="", provider="openai")
    check("بدون کلید → available=False", not s2.available)

    s3 = LLMService(api_key="", provider="ollama")
    check("ollama بدون کلید کار می‌کند", s3.available)
    check("ollama → localhost", "localhost:11434" in str(s3._client.base_url))  # noqa: SLF001

    s4 = LLMService(api_key="sk-x", provider="gemini")
    check("gemini base", "generativelanguage" in str(s4._client.base_url))  # noqa: SLF001


def test_settings_integration() -> None:
    print("\n۴) یکپارچگی با settings")
    import os
    from config.settings import Settings

    os.environ["LLM_PROVIDER"] = "groq"
    os.environ["GROQ_API_KEY"] = "gsk_abc"
    os.environ["OPENAI_API_KEY"] = "sk_xyz"
    st = Settings()
    check("provider خوانده شد", st.llm_provider == "groq", st.llm_provider)
    check("کلید فعال = groq", st.active_llm_key == "gsk_abc", st.active_llm_key)

    os.environ["LLM_PROVIDER"] = "openai"
    st2 = Settings()
    check("سوییچ به openai", st2.active_llm_key == "sk_xyz", st2.active_llm_key)


def test_cost_math() -> None:
    print("\n۵) ریاضیات هزینه")
    from tools.cost import TOKENS, cost_per_call, input_tokens

    in_tok = input_tokens()
    check("ورودی ≈ ۱۷۵۰", 1500 < in_tok < 2000, in_tok)

    mini = cost_per_call("gpt-4o-mini", in_tok, TOKENS["answer"])
    full = cost_per_call("gpt-4o", in_tok, TOKENS["answer"])
    check("mini ارزان‌تر از 4o", mini < full)
    check("نسبت ≈ ۱۶×", 12 < full / mini < 20, f"{full / mini:.1f}")

    free = cost_per_call("meta-llama/llama-3.3-70b-instruct:free", in_tok, TOKENS["answer"])
    check("مدل :free صفر است", free == 0)

    check("ollama صفر است", cost_per_call("ollama", in_tok, 400) == 0)

    # یک ماه با ۲۰ وظیفه/روز
    monthly = mini * 20 * 30
    check(f"gpt-4o-mini با ۲۰/روز → ${monthly:.3f}/ماه", monthly < 1.5, monthly)


def main() -> int:
    print("=" * 66)
    print("  تست: ارائه‌دهنده‌های LLM و هزینه")
    print("=" * 66)
    test_base_urls()
    test_free_models()
    test_client_build()
    test_settings_integration()
    test_cost_math()
    print("\n" + "=" * 66)
    print(f"  نتیجه: {PASS} ✅ / {FAIL} ❌")
    print("=" * 66)
    return 0 if FAIL == 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())
