"""
Classroom API - Settings Endpoints.

Endpoints fuer Lehrer-Einstellungen.
"""

from typing import Dict, Optional, Any
from datetime import datetime
import logging

from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field

from classroom_engine import get_default_durations

from .shared import init_db_if_needed, DB_ENABLED, logger

try:
    from classroom_engine.database import SessionLocal
    from classroom_engine.repository import TeacherSettingsRepository
except ImportError:
    pass

router = APIRouter(tags=["Settings"])

# In-Memory Storage (Fallback)
_settings: Dict[str, dict] = {}


# === Pydantic Models ===

class PhaseDurationsUpdate(BaseModel):
    """Update fuer Phasendauern."""
    einstieg: Optional[int] = Field(None, ge=1, le=30)
    erarbeitung: Optional[int] = Field(None, ge=5, le=45)
    sicherung: Optional[int] = Field(None, ge=3, le=20)
    transfer: Optional[int] = Field(None, ge=3, le=20)
    reflexion: Optional[int] = Field(None, ge=2, le=15)


class PreferencesUpdate(BaseModel):
    """Update fuer Lehrer-Praeferenzen."""
    auto_advance: Optional[bool] = None
    sound_enabled: Optional[bool] = None
    notification_enabled: Optional[bool] = None
    theme: Optional[str] = None
    language: Optional[str] = None


class TeacherSettingsResponse(BaseModel):
    """Response fuer Lehrer-Einstellungen."""
    teacher_id: str
    phase_durations: Dict[str, int]
    preferences: Dict[str, Any]
    created_at: str
    updated_at: Optional[str]


# === Helper Functions ===

def get_default_settings(teacher_id: str) -> dict:
    """Gibt die Default-Einstellungen zurueck."""
    return {
        "teacher_id": teacher_id,
        "phase_durations": get_default_durations(),
        "preferences": {
            "auto_advance": False,
            "sound_enabled": True,
            "notification_enabled": True,
            "theme": "light",
            "language": "de",
        },
        "created_at": datetime.utcnow().isoformat(),
        "updated_at": None,
    }


# === Endpoints ===

@router.get("/settings/{teacher_id}", response_model=TeacherSettingsResponse)
async def get_teacher_settings(teacher_id: str) -> TeacherSettingsResponse:
    """Ruft die Einstellungen eines Lehrers ab."""
    init_db_if_needed()

    # Aus Memory pruefen
    if teacher_id in _settings:
        return TeacherSettingsResponse(**_settings[teacher_id])

    # Aus DB laden
    if DB_ENABLED:
        try:
            db = SessionLocal()
            repo = TeacherSettingsRepository(db)
            db_settings = repo.get_by_teacher(teacher_id)
            db.close()

            if db_settings:
                settings_data = repo.to_dict(db_settings)
                _settings[teacher_id] = settings_data
                return TeacherSettingsResponse(**settings_data)
        except Exception as e:
            logger.warning(f"DB read failed for settings: {e}")

    # Default-Einstellungen erstellen
    settings_data = get_default_settings(teacher_id)
    _settings[teacher_id] = settings_data

    if DB_ENABLED:
        try:
            db = SessionLocal()
            repo = TeacherSettingsRepository(db)
            repo.create(settings_data)
            db.close()
        except Exception as e:
            logger.warning(f"DB persist failed for settings: {e}")

    return TeacherSettingsResponse(**settings_data)


@router.put("/settings/{teacher_id}/durations", response_model=TeacherSettingsResponse)
async def update_phase_durations(
    teacher_id: str,
    request: PhaseDurationsUpdate
) -> TeacherSettingsResponse:
    """Aktualisiert die Phasendauern eines Lehrers."""
    init_db_if_needed()

    # Aktuelle Einstellungen laden
    current = await get_teacher_settings(teacher_id)
    settings_data = _settings.get(teacher_id, get_default_settings(teacher_id))

    # Nur uebergebene Werte aktualisieren
    durations = settings_data["phase_durations"]
    if request.einstieg is not None:
        durations["einstieg"] = request.einstieg
    if request.erarbeitung is not None:
        durations["erarbeitung"] = request.erarbeitung
    if request.sicherung is not None:
        durations["sicherung"] = request.sicherung
    if request.transfer is not None:
        durations["transfer"] = request.transfer
    if request.reflexion is not None:
        durations["reflexion"] = request.reflexion

    settings_data["phase_durations"] = durations
    settings_data["updated_at"] = datetime.utcnow().isoformat()

    # In DB speichern
    if DB_ENABLED:
        try:
            db = SessionLocal()
            repo = TeacherSettingsRepository(db)
            repo.update_durations(teacher_id, durations)
            db.close()
        except Exception as e:
            logger.warning(f"DB update failed for durations: {e}")

    _settings[teacher_id] = settings_data
    return TeacherSettingsResponse(**settings_data)


@router.put("/settings/{teacher_id}/preferences", response_model=TeacherSettingsResponse)
async def update_preferences(
    teacher_id: str,
    request: PreferencesUpdate
) -> TeacherSettingsResponse:
    """Aktualisiert die Praeferenzen eines Lehrers."""
    init_db_if_needed()

    # Aktuelle Einstellungen laden
    current = await get_teacher_settings(teacher_id)
    settings_data = _settings.get(teacher_id, get_default_settings(teacher_id))

    # Nur uebergebene Werte aktualisieren
    prefs = settings_data["preferences"]
    if request.auto_advance is not None:
        prefs["auto_advance"] = request.auto_advance
    if request.sound_enabled is not None:
        prefs["sound_enabled"] = request.sound_enabled
    if request.notification_enabled is not None:
        prefs["notification_enabled"] = request.notification_enabled
    if request.theme is not None:
        prefs["theme"] = request.theme
    if request.language is not None:
        prefs["language"] = request.language

    settings_data["preferences"] = prefs
    settings_data["updated_at"] = datetime.utcnow().isoformat()

    # In DB speichern
    if DB_ENABLED:
        try:
            db = SessionLocal()
            repo = TeacherSettingsRepository(db)
            repo.update_preferences(teacher_id, prefs)
            db.close()
        except Exception as e:
            logger.warning(f"DB update failed for preferences: {e}")

    _settings[teacher_id] = settings_data
    return TeacherSettingsResponse(**settings_data)
