# app/modules/loyalty/routes/api/platform.py
"""
Loyalty module platform routes.

Platform endpoints for:
- Customer enrollment (by vendor code)
- Apple Wallet pass download
- Apple Web Service endpoints for device registration/updates
"""

import logging
from datetime import UTC, datetime

from fastapi import APIRouter, Depends, Header, HTTPException, Path, Response
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.modules.loyalty.exceptions import (
    LoyaltyCardNotFoundException,
    LoyaltyException,
    LoyaltyProgramNotFoundException,
)
from app.modules.loyalty.models import LoyaltyCard, LoyaltyProgram
from app.modules.loyalty.services import (
    apple_wallet_service,
    card_service,
    program_service,
)

logger = logging.getLogger(__name__)

# Platform router (no auth required for some endpoints)
platform_router = APIRouter(prefix="/loyalty")


# =============================================================================
# Enrollment
# =============================================================================


@platform_router.get("/programs/{vendor_code}")
def get_program_by_vendor_code(
    vendor_code: str = Path(..., min_length=1, max_length=50),
    db: Session = Depends(get_db),
):
    """Get loyalty program info by vendor code (for enrollment page)."""
    from app.modules.tenancy.models import Vendor

    # Find vendor by code (vendor_code or subdomain)
    vendor = (
        db.query(Vendor)
        .filter(
            (Vendor.vendor_code == vendor_code) | (Vendor.subdomain == vendor_code)
        )
        .first()
    )
    if not vendor:
        raise HTTPException(status_code=404, detail="Vendor not found")

    # Get program
    program = program_service.get_active_program_by_vendor(db, vendor.id)
    if not program:
        raise HTTPException(status_code=404, detail="No active loyalty program")

    return {
        "vendor_name": vendor.name,
        "vendor_code": vendor.vendor_code,
        "program": {
            "id": program.id,
            "type": program.loyalty_type,
            "name": program.display_name,
            "card_color": program.card_color,
            "logo_url": program.logo_url,
            "stamps_target": program.stamps_target if program.is_stamps_enabled else None,
            "stamps_reward": program.stamps_reward_description if program.is_stamps_enabled else None,
            "points_per_euro": program.points_per_euro if program.is_points_enabled else None,
            "terms_text": program.terms_text,
            "privacy_url": program.privacy_url,
        },
    }


# =============================================================================
# Apple Wallet Pass Download
# =============================================================================


@platform_router.get("/passes/apple/{serial_number}.pkpass")
def download_apple_pass(
    serial_number: str = Path(...),
    db: Session = Depends(get_db),
):
    """Download Apple Wallet pass for a card."""
    # Find card by serial number
    card = (
        db.query(LoyaltyCard)
        .filter(LoyaltyCard.apple_serial_number == serial_number)
        .first()
    )

    if not card:
        raise HTTPException(status_code=404, detail="Pass not found")

    try:
        pass_data = apple_wallet_service.generate_pass(db, card)
    except LoyaltyException as e:
        logger.error(f"Failed to generate Apple pass for card {card.id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to generate pass")

    return Response(
        content=pass_data,
        media_type="application/vnd.apple.pkpass",
        headers={
            "Content-Disposition": f'attachment; filename="{serial_number}.pkpass"',
        },
    )


# =============================================================================
# Apple Web Service Endpoints
# (Required for Apple Wallet to register devices and get updates)
# =============================================================================


@platform_router.post("/apple/v1/devices/{device_id}/registrations/{pass_type_id}/{serial_number}")
def register_device(
    device_id: str = Path(...),
    pass_type_id: str = Path(...),
    serial_number: str = Path(...),
    authorization: str | None = Header(None),
    db: Session = Depends(get_db),
):
    """
    Register a device for push notifications.

    Called by Apple when user adds pass to wallet.
    """
    # Validate authorization token
    auth_token = None
    if authorization and authorization.startswith("ApplePass "):
        auth_token = authorization.split(" ", 1)[1]

    # Find card
    card = (
        db.query(LoyaltyCard)
        .filter(LoyaltyCard.apple_serial_number == serial_number)
        .first()
    )

    if not card:
        raise HTTPException(status_code=404)

    # Verify auth token
    if not auth_token or auth_token != card.apple_auth_token:
        raise HTTPException(status_code=401)

    # Get push token from request body
    # Note: In real implementation, parse the JSON body for pushToken
    # For now, use device_id as a placeholder
    try:
        apple_wallet_service.register_device(db, card, device_id, device_id)
        return Response(status_code=201)
    except Exception as e:
        logger.error(f"Failed to register device: {e}")
        raise HTTPException(status_code=500)


@platform_router.delete("/apple/v1/devices/{device_id}/registrations/{pass_type_id}/{serial_number}")
def unregister_device(
    device_id: str = Path(...),
    pass_type_id: str = Path(...),
    serial_number: str = Path(...),
    authorization: str | None = Header(None),
    db: Session = Depends(get_db),
):
    """
    Unregister a device.

    Called by Apple when user removes pass from wallet.
    """
    # Validate authorization token
    auth_token = None
    if authorization and authorization.startswith("ApplePass "):
        auth_token = authorization.split(" ", 1)[1]

    # Find card
    card = (
        db.query(LoyaltyCard)
        .filter(LoyaltyCard.apple_serial_number == serial_number)
        .first()
    )

    if not card:
        raise HTTPException(status_code=404)

    # Verify auth token
    if not auth_token or auth_token != card.apple_auth_token:
        raise HTTPException(status_code=401)

    try:
        apple_wallet_service.unregister_device(db, card, device_id)
        return Response(status_code=200)
    except Exception as e:
        logger.error(f"Failed to unregister device: {e}")
        raise HTTPException(status_code=500)


@platform_router.get("/apple/v1/devices/{device_id}/registrations/{pass_type_id}")
def get_serial_numbers(
    device_id: str = Path(...),
    pass_type_id: str = Path(...),
    passesUpdatedSince: str | None = None,
    db: Session = Depends(get_db),
):
    """
    Get list of pass serial numbers to update.

    Called by Apple to check for updated passes.
    """
    from app.modules.loyalty.models import AppleDeviceRegistration

    # Find all cards registered to this device
    registrations = (
        db.query(AppleDeviceRegistration)
        .filter(AppleDeviceRegistration.device_library_identifier == device_id)
        .all()
    )

    if not registrations:
        return Response(status_code=204)

    # Get cards that have been updated since the given timestamp
    card_ids = [r.card_id for r in registrations]

    query = db.query(LoyaltyCard).filter(LoyaltyCard.id.in_(card_ids))

    if passesUpdatedSince:
        try:
            since = datetime.fromisoformat(passesUpdatedSince.replace("Z", "+00:00"))
            query = query.filter(LoyaltyCard.updated_at > since)
        except ValueError:
            pass

    cards = query.all()

    if not cards:
        return Response(status_code=204)

    # Return serial numbers
    serial_numbers = [card.apple_serial_number for card in cards if card.apple_serial_number]
    last_updated = max(card.updated_at for card in cards)

    return {
        "serialNumbers": serial_numbers,
        "lastUpdated": last_updated.isoformat(),
    }


@platform_router.get("/apple/v1/passes/{pass_type_id}/{serial_number}")
def get_latest_pass(
    pass_type_id: str = Path(...),
    serial_number: str = Path(...),
    authorization: str | None = Header(None),
    db: Session = Depends(get_db),
):
    """
    Get the latest version of a pass.

    Called by Apple to fetch updated pass data.
    """
    # Validate authorization token
    auth_token = None
    if authorization and authorization.startswith("ApplePass "):
        auth_token = authorization.split(" ", 1)[1]

    # Find card
    card = (
        db.query(LoyaltyCard)
        .filter(LoyaltyCard.apple_serial_number == serial_number)
        .first()
    )

    if not card:
        raise HTTPException(status_code=404)

    # Verify auth token
    if not auth_token or auth_token != card.apple_auth_token:
        raise HTTPException(status_code=401)

    try:
        pass_data = apple_wallet_service.generate_pass(db, card)
    except LoyaltyException as e:
        logger.error(f"Failed to generate Apple pass for card {card.id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to generate pass")

    return Response(
        content=pass_data,
        media_type="application/vnd.apple.pkpass",
        headers={
            "Last-Modified": card.updated_at.strftime("%a, %d %b %Y %H:%M:%S GMT"),
        },
    )


@platform_router.post("/apple/v1/log")
def log_errors():
    """
    Receive error logs from Apple.

    Apple sends error logs here when there are issues with passes.
    """
    # Just acknowledge - in production you'd log these
    return Response(status_code=200)
