from __future__ import annotations

import os

from ebay_client import EbayClient
from ebay_client.core.auth.models import EbayOAuthConfig
from ebay_client.generated.inventory.models import (
    Amount,
    Availability,
    EbayOfferDetailsWithKeys,
    InventoryItem,
    ListingPolicies,
    PricingSummary,
    Product,
    ShipToLocationAvailability,
)


def require_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Environment variable {name} is required")
    return value


def build_client() -> EbayClient:
    oauth_config = EbayOAuthConfig(
        client_id=require_env("EBAY_CLIENT_ID"),
        client_secret=require_env("EBAY_CLIENT_SECRET"),
        default_scopes=["https://api.ebay.com/oauth/api_scope/sell.inventory"],
    )
    return EbayClient(oauth_config)


def build_inventory_item() -> InventoryItem:
    return InventoryItem(
        condition="NEW",
        availability=Availability(
            shipToLocationAvailability=ShipToLocationAvailability(quantity=int(os.environ.get("EBAY_AVAILABLE_QUANTITY", "1")))
        ),
        product=Product(
            title=require_env("EBAY_ITEM_TITLE"),
            description=require_env("EBAY_ITEM_DESCRIPTION"),
            imageUrls=[require_env("EBAY_ITEM_IMAGE_URL")],
            aspects='{"Brand":["Demo Brand"],"Type":["Demo Item"]}',
        ),
    )


def build_offer_payload(sku: str) -> EbayOfferDetailsWithKeys:
    return EbayOfferDetailsWithKeys(
        sku=sku,
        marketplaceId=os.environ.get("EBAY_MARKETPLACE_ID", "EBAY_US"),
        format="FIXED_PRICE",
        availableQuantity=int(os.environ.get("EBAY_AVAILABLE_QUANTITY", "1")),
        categoryId=require_env("EBAY_CATEGORY_ID"),
        merchantLocationKey=require_env("EBAY_MERCHANT_LOCATION_KEY"),
        listingDescription=os.environ.get("EBAY_LISTING_DESCRIPTION") or require_env("EBAY_ITEM_DESCRIPTION"),
        listingDuration="GTC",
        listingPolicies=ListingPolicies(
            fulfillmentPolicyId=require_env("EBAY_FULFILLMENT_POLICY_ID"),
            paymentPolicyId=require_env("EBAY_PAYMENT_POLICY_ID"),
            returnPolicyId=require_env("EBAY_RETURN_POLICY_ID"),
        ),
        pricingSummary=PricingSummary(
            price=Amount(
                currency=os.environ.get("EBAY_CURRENCY", "USD"),
                value=require_env("EBAY_PRICE"),
            )
        ),
    )


def main() -> None:
    client = build_client()
    sku = require_env("EBAY_SKU")
    content_language = os.environ.get("EBAY_CONTENT_LANGUAGE", "en-US")

    item_result = client.inventory.create_or_replace_inventory_item(
        sku,
        build_inventory_item(),
        content_language=content_language,
    )
    print("inventory_item_warnings:", item_result.warnings)

    offer = client.inventory.create_offer(
        build_offer_payload(sku),
        content_language=content_language,
    )
    print("offer_id:", offer.offerId)

    if not offer.offerId:
        raise RuntimeError("create_offer did not return an offerId")

    published = client.inventory.publish_offer(offer.offerId)
    print("listing_id:", published.listingId)


if __name__ == "__main__":
    main()