"""Seed categories, products and settings. Safe to run repeatedly."""
import asyncio
import sys
from decimal import Decimal
from pathlib import Path

sys.path.append(str(Path(__file__).resolve().parents[1]))

from app.core.database import SessionFactory  # noqa: E402
from app.repositories import CategoryRepository, ProductRepository  # noqa: E402
from app.services import AuthService, SettingsService  # noqa: E402

CATEGORIES = [
    {"title": "پرمیوم", "slug": "premium", "icon": "⭐️", "sort_order": 1},
    {"title": "استارز", "slug": "stars", "icon": "✨", "sort_order": 2},
    {"title": "خرید ارز TON", "slug": "ton", "icon": "💎", "sort_order": 3},
    {"title": "شارژ TON Balance", "slug": "ton-balance", "icon": "🔋", "sort_order": 4},
    {"title": "گیفت استارزی", "slug": "gift", "icon": "🎁", "sort_order": 5},
    {"title": "بوست تلگرام", "slug": "boost", "icon": "🚀", "sort_order": 6},
    {"title": "گیواوی استارزی", "slug": "giveaway", "icon": "🎉", "sort_order": 7},
    {"title": "ری اکشن استارزی", "slug": "reaction", "icon": "❤️", "sort_order": 8},
]

PRODUCTS = [
    # premium
    {"category": "premium", "title": "پرمیوم ۳ ماهه", "slug": "premium-3m", "price": "850000",
     "flow": "premium", "sort_order": 1, "data": {"months": 3}},
    {"category": "premium", "title": "پرمیوم ۶ ماهه", "slug": "premium-6m", "price": "1150000",
     "flow": "premium", "sort_order": 2, "data": {"months": 6}},
    {"category": "premium", "title": "پرمیوم ۱۲ ماهه", "slug": "premium-12m", "price": "1950000",
     "flow": "premium", "sort_order": 3, "data": {"months": 12}},
    # stars
    {"category": "stars", "title": "۵۰ استارز", "slug": "stars-50", "price": "75000",
     "flow": "stars", "sort_order": 1, "data": {"count": 50}},
    {"category": "stars", "title": "۱۰۰ استارز", "slug": "stars-100", "price": "145000",
     "flow": "stars", "sort_order": 2, "data": {"count": 100}},
    {"category": "stars", "title": "۵۰۰ استارز", "slug": "stars-500", "price": "700000",
     "flow": "stars", "sort_order": 3, "data": {"count": 500}},
    {"category": "stars", "title": "۱۰۰۰ استارز", "slug": "stars-1000", "price": "1380000",
     "flow": "stars", "sort_order": 4, "data": {"count": 1000}},
    # ton (price is calculated from the TON rate setting)
    {"category": "ton", "title": "خرید ارز TON", "slug": "ton-buy", "price": "0",
     "flow": "ton", "sort_order": 1, "data": {"network": "TON"}},
    {"category": "ton-balance", "title": "شارژ TON Balance", "slug": "ton-balance", "price": "0",
     "flow": "ton_balance", "sort_order": 1, "data": {"network": "TON"}},
    # gift
    {"category": "gift", "title": "گیفت ۱۰۰ استارز", "slug": "gift-100", "price": "160000",
     "flow": "gift", "sort_order": 1,
     "data": {"stars": 100, "allow_hide": True, "allow_comment": True}},
    {"category": "gift", "title": "گیفت ۵۰۰ استارز", "slug": "gift-500", "price": "740000",
     "flow": "gift", "sort_order": 2,
     "data": {"stars": 500, "allow_hide": True, "allow_comment": True}},
    {"category": "gift", "title": "گیفت ۱۰۰۰ استارز", "slug": "gift-1000", "price": "1450000",
     "flow": "gift", "sort_order": 3,
     "data": {"stars": 1000, "allow_hide": True, "allow_comment": True}},
    # boost (per unit)
    {"category": "boost", "title": "بوست تضمین ۱ الی ۵ روز", "slug": "boost-fast", "price": "45000",
     "flow": "boost", "sort_order": 1,
     "data": {"per_unit": True, "plan": "fast", "min_quantity": 1, "max_quantity": 1000}},
    {"category": "boost", "title": "بوست تضمین ۲۰ الی ۳۰ روز", "slug": "boost-normal",
     "price": "28000", "flow": "boost", "sort_order": 2,
     "data": {"per_unit": True, "plan": "normal", "min_quantity": 1, "max_quantity": 1000}},
    # giveaway
    {"category": "giveaway", "title": "گیواوی ۵۰۰ استارز", "slug": "giveaway-500", "price": "780000",
     "flow": "giveaway", "sort_order": 1, "data": {"stars": 500, "winners": 5}},
    {"category": "giveaway", "title": "گیواوی ۱۰۰۰ استارز", "slug": "giveaway-1000",
     "price": "1490000", "flow": "giveaway", "sort_order": 2, "data": {"stars": 1000, "winners": 10}},
    # reaction
    {"category": "reaction", "title": "ری اکشن استارزی", "slug": "reaction-star", "price": "9000",
     "flow": "reaction", "sort_order": 1,
     "data": {"per_unit": True, "count": 1, "min_quantity": 10, "max_quantity": 100000}},
]


async def seed() -> None:
    async with SessionFactory() as session:
        categories_repo = CategoryRepository(session)
        products_repo = ProductRepository(session)

        category_ids: dict[str, object] = {}
        for item in CATEGORIES:
            category = await categories_repo.get_by_slug(item["slug"])
            if not category:
                category = await categories_repo.create(**item)
                print(f"category created: {item['slug']}")
            category_ids[item["slug"]] = category.id

        for item in PRODUCTS:
            if await products_repo.get_by_slug(item["slug"]):
                continue
            payload = dict(item)
            payload["category_id"] = category_ids[payload.pop("category")]
            payload["price"] = Decimal(payload["price"])
            await products_repo.create(**payload)
            print(f"product created: {item['slug']}")

        await SettingsService(session).ensure_defaults()
        admin = await AuthService(session).ensure_default_admin()
        print(f"admin ready: {admin.username}")

        await session.commit()
    print("seed complete")


if __name__ == "__main__":
    asyncio.run(seed())
