#!/usr/bin/env python3
"""
Deck URL Validator - Task #117 Stream A

Validates deck URLs for accessibility and provides fallback handling.
Supports GitHub Pages, Railway-hosted, and localhost URLs.
"""

import logging
import aiohttp
from typing import Optional

logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

# TODO: Update to the correct URL
class DeckURLValidator:
    """
    Validates deck URLs for accessibility before bot starts streaming.

    Supports multiple URL types:
    - GitHub Pages: https://buzztrail.github.io/buzztrail-presentations/{deck-id}/
    - Railway: https://slide-system-production-5813.up.railway.app/decks/{deck-id}/
    - Localhost: http://localhost:8080/ (for testing)

    Usage:
        validator = DeckURLValidator()
        is_valid = await validator.validate_url("https://example.com/deck/")
        if not is_valid:
            fallback = validator.get_fallback_deck_url()
    """

    # Fallback test deck URL
    FALLBACK_DECK_URL = "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/"

    # Validation timeout in seconds
    TIMEOUT_SECONDS = 5

    @staticmethod
    async def validate_url(deck_url: str) -> bool:
        """
        Check if deck URL is accessible via HTTP HEAD request.

        Args:
            deck_url: The URL to validate

        Returns:
            True if URL returns 200 OK, False otherwise

        Implementation:
            - Sends HTTP HEAD request with 5-second timeout
            - Validates 200 OK response
            - Handles network errors gracefully
            - Logs validation results
        """
        if not deck_url:
            logger.error("Deck URL validation failed: URL is empty")
            return False

        try:
            logger.info(f"Validating deck URL: {deck_url}")

            # Create timeout configuration
            timeout = aiohttp.ClientTimeout(total=DeckURLValidator.TIMEOUT_SECONDS)

            # Send HEAD request to check URL accessibility
            async with aiohttp.ClientSession(timeout=timeout) as session:
                async with session.head(deck_url, allow_redirects=True) as response:
                    if response.status == 200:
                        logger.info(f"✅ Deck URL validated successfully: {deck_url}")
                        return True
                    else:
                        logger.error(
                            f"❌ Deck URL validation failed: "
                            f"HTTP {response.status} - {deck_url}"
                        )
                        return False

        except aiohttp.ClientError as e:
            logger.error(f"❌ Deck URL validation failed (client error): {e}")
            logger.error(f"   URL: {deck_url}")
            return False

        except asyncio.TimeoutError:
            logger.error(
                f"❌ Deck URL validation timeout "
                f"(exceeded {DeckURLValidator.TIMEOUT_SECONDS}s): {deck_url}"
            )
            return False

        except Exception as e:
            logger.error(f"❌ Deck URL validation failed (unexpected error): {e}")
            logger.error(f"   URL: {deck_url}")
            return False

    @staticmethod
    def get_fallback_deck_url() -> str:
        """
        Return premade test deck URL as fallback.

        Returns:
            Fallback deck URL (GitHub Pages hosted test deck)

        Usage:
            Called when dynamic deck URL validation fails to provide
            a known-good deck URL for reliable streaming.
        """
        logger.info(f"📄 Using fallback deck URL: {DeckURLValidator.FALLBACK_DECK_URL}")
        return DeckURLValidator.FALLBACK_DECK_URL


# For async import requirement
import asyncio


# CLI test utility
async def main() -> bool:
    """Test utility for validating deck URLs from command line"""
    import sys

    if len(sys.argv) < 2:
        print("Usage: python deck_url_validator.py <deck_url>")
        print()
        print("Examples:")
        print("  python deck_url_validator.py https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/")
        print("  python deck_url_validator.py http://localhost:8080/")
        print()
        print("Tests if a deck URL is accessible and returns validation status.")
        sys.exit(1)

    deck_url = sys.argv[1]

    logger.info("=" * 60)
    logger.info("DECK URL VALIDATOR TEST")
    logger.info(f"URL: {deck_url}")
    logger.info("=" * 60)

    # Test validation
    is_valid = await DeckURLValidator.validate_url(deck_url)

    if is_valid:
        logger.info("🎉 Result: URL is valid and accessible")
    else:
        logger.warning("⚠️ Result: URL is invalid or inaccessible")
        fallback = DeckURLValidator.get_fallback_deck_url()
        logger.info(f"💡 Fallback URL available: {fallback}")

    logger.info("=" * 60)

    return is_valid


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