"""Session management service."""

import random
from datetime import datetime, timedelta
from typing import Optional
import uuid

from ..database import db
from ..models import Session


class SessionService:
    """Service for managing anonymous user sessions via magic phrases."""

    # Curated word lists for memorable phrases
    ADJECTIVES = [
        "fishy",
        "salty",
        "bitter",
        "sweet",
        "spicy",
        "funky",
        "tangy",
        "fuzzy",
        "sticky",
        "slippery",
        "bouncy",
        "shiny",
        "crispy",
        "fluffy",
        "gooey",
    ]

    NOUNS = [
        "entanglement",
        "adventure",
        "discovery",
        "wilderness",
        "carnival",
        "sunset",
        "thunder",
        "silence",
        "whisper",
        "mystery",
        "treasure",
        "symphony",
        "eclipse",
        "cascade",
        "meadow",
    ]

    OBJECTS = [
        "harpoon",
        "telescope",
        "compass",
        "pyramid",
        "volcano",
        "lighthouse",
        "fortress",
        "canyon",
        "glacier",
        "waterfall",
        "mansion",
        "cathedral",
        "lantern",
        "anchor",
        "windmill",
    ]

    ACTIONS = [
        "deduction",
        "celebration",
        "observation",
        "revelation",
        "transformation",
        "destruction",
        "construction",
        "exploration",
        "meditation",
        "fascination",
        "dedication",
        "violation",
        "navigation",
        "creation",
        "innovation",
    ]

    @staticmethod
    def generate_phrase() -> str:
        """Generate a memorable 4-word magic phrase.

        Format: "adjective-noun-object-action"

        Returns:
            A unique magic phrase (e.g., "fishy-entanglement-harpoon-deduction")
        """
        parts = [
            random.choice(SessionService.ADJECTIVES),
            random.choice(SessionService.NOUNS),
            random.choice(SessionService.OBJECTS),
            random.choice(SessionService.ACTIONS),
        ]
        return "-".join(parts)

    @staticmethod
    def create_session() -> Session:
        """Create a new session with a unique magic phrase.

        Returns:
            New Session object (not yet committed to database)
        """
        # Generate unique phrase
        while True:
            magic_phrase = SessionService.generate_phrase()
            existing = Session.query.filter_by(magic_phrase=magic_phrase).first()
            if not existing:
                break

        # Create session
        session = Session(
            id=str(uuid.uuid4()),
            magic_phrase=magic_phrase,
            created_at=datetime.utcnow(),
            last_accessed_at=datetime.utcnow(),
            expires_at=datetime.utcnow() + timedelta(days=365),
        )

        return session

    @staticmethod
    def get_session_by_phrase(magic_phrase: str) -> Optional[Session]:
        """Get session by magic phrase.

        Args:
            magic_phrase: The magic phrase to look up

        Returns:
            Session object if found and not expired, None otherwise
        """
        session = Session.query.filter_by(magic_phrase=magic_phrase).first()

        if not session:
            return None

        # Check if expired
        if session.expires_at < datetime.utcnow():
            return None

        # Update last accessed time and extend expiration by 1 year
        now = datetime.utcnow()
        session.last_accessed_at = now
        session.expires_at = now + timedelta(days=365)
        db.session.commit()

        return session

    @staticmethod
    def validate_phrase(phrase: str) -> bool:
        """Check if phrase matches expected format.

        Args:
            phrase: Magic phrase to validate

        Returns:
            True if phrase has 4 parts separated by hyphens
        """
        parts = phrase.split("-")
        return len(parts) == 4
