import os
import hashlib
import time
import logging

logger = logging.getLogger(__name__)

STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "")
STRIPE_WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET", "")

LISTING_PRICES = {
    "starter": 29700,
    "professional": 39700,
    "premium": 49700,
}

ALLOWED_TIERS = set(LISTING_PRICES.keys())


def _get_stripe():
    try:
        import stripe
        stripe.api_key = STRIPE_SECRET_KEY
        return stripe
    except ImportError:
        raise RuntimeError("stripe package not installed")


def create_checkout_session(domain: str, tier: str, success_url: str, cancel_url: str) -> dict:
    if tier not in ALLOWED_TIERS:
        raise ValueError(f"Invalid tier: {tier}. Must be one of: {', '.join(ALLOWED_TIERS)}")
    if not STRIPE_SECRET_KEY:
        raise RuntimeError("Stripe is not configured. Set STRIPE_SECRET_KEY environment variable.")
    stripe = _get_stripe()
    price_cents = LISTING_PRICES[tier]
    session = stripe.checkout.Session.create(
        payment_method_types=["card"],
        line_items=[{
            "price_data": {
                "currency": "usd",
                "product_data": {
                    "name": f"Website Package: {domain}",
                    "description": f"{tier.title()} tier website package with full source code, content, and assets",
                },
                "unit_amount": price_cents,
            },
            "quantity": 1,
        }],
        mode="payment",
        success_url=success_url,
        cancel_url=cancel_url,
        metadata={"domain": domain, "tier": tier},
    )
    return {"checkout_url": session.url, "session_id": session.id}


def verify_webhook_signature(payload: bytes, sig_header: str) -> dict:
    stripe = _get_stripe()
    event = stripe.Webhook.construct_event(payload, sig_header, STRIPE_WEBHOOK_SECRET)
    return event


def generate_download_token(domain: str) -> str:
    raw = f"{domain}:{time.time()}:{os.urandom(16).hex()}"
    return hashlib.sha256(raw.encode()).hexdigest()[:32]


_download_tokens = {}


def store_download_token(token: str, domain: str):
    _download_tokens[token] = {"domain": domain, "created": time.time(), "valid": True}


def validate_download_token(token: str) -> dict:
    entry = _download_tokens.get(token)
    if not entry:
        return {"valid": False}
    if time.time() - entry["created"] > 86400:
        return {"valid": False}
    return {"domain": entry["domain"], "valid": True}
