from __future__ import annotations

from fastapi import APIRouter, HTTPException, Depends, status
from typing import Any, Dict, List
from sqlalchemy.orm import Session

from app.services.settings import get_models, update_models, get_exchanges, update_exchanges
from app.db.database import get_db
from app.models.models import UserIndicatorPreferences
from app.schemas.schemas import (
    IndicatorPreferenceCreate,
    IndicatorPreferenceUpdate,
    IndicatorPreferenceResponse,
    IndicatorPreferencesListResponse
)

router = APIRouter(prefix="/settings", tags=["Settings"]) 


@router.get("/models")
async def models_get() -> Dict[str, Any]:
    return get_models()


@router.put("/models")
async def models_put(patch: Dict[str, Any]) -> Dict[str, Any]:
    return update_models(patch)


@router.get("/exchanges")
async def exchanges_get() -> Dict[str, Any]:
    return get_exchanges()


@router.put("/exchanges")
async def exchanges_put(patch: Dict[str, Any]) -> Dict[str, Any]:
    return update_exchanges(patch)


# ============================================================================
# INDICATOR PREFERENCES ENDPOINTS
# ============================================================================

@router.get("/indicators/preferences", response_model=IndicatorPreferencesListResponse)
async def get_indicator_preferences(
    user_id: str = None,
    enabled_only: bool = False,
    db: Session = Depends(get_db)
):
    """Get user's indicator preferences"""
    query = db.query(UserIndicatorPreferences)
    
    if user_id:
        query = query.filter(UserIndicatorPreferences.user_id == user_id)
    
    if enabled_only:
        query = query.filter(UserIndicatorPreferences.enabled == True)
    
    preferences = query.order_by(UserIndicatorPreferences.priority.desc()).all()
    
    return {
        "preferences": preferences,
        "total": len(preferences)
    }


@router.post("/indicators/preferences", response_model=IndicatorPreferenceResponse, status_code=status.HTTP_201_CREATED)
async def create_indicator_preference(
    preference: IndicatorPreferenceCreate,
    user_id: str = None,
    db: Session = Depends(get_db)
):
    """Create a new indicator preference"""
    # Check if indicator already exists for this user
    existing = db.query(UserIndicatorPreferences).filter(
        UserIndicatorPreferences.user_id == user_id,
        UserIndicatorPreferences.indicator_name == preference.indicator_name
    ).first()
    
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Preference for indicator '{preference.indicator_name}' already exists"
        )
    
    db_preference = UserIndicatorPreferences(
        user_id=user_id,
        **preference.dict()
    )
    db.add(db_preference)
    db.commit()
    db.refresh(db_preference)
    return db_preference


@router.put("/indicators/preferences/{preference_id}", response_model=IndicatorPreferenceResponse)
async def update_indicator_preference(
    preference_id: int,
    preference_update: IndicatorPreferenceUpdate,
    db: Session = Depends(get_db)
):
    """Update an indicator preference"""
    db_preference = db.query(UserIndicatorPreferences).filter(
        UserIndicatorPreferences.id == preference_id
    ).first()
    
    if not db_preference:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Indicator preference not found"
        )
    
    update_data = preference_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_preference, key, value)
    
    db.commit()
    db.refresh(db_preference)
    return db_preference


@router.delete("/indicators/preferences/{preference_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_indicator_preference(
    preference_id: int,
    db: Session = Depends(get_db)
):
    """Delete an indicator preference"""
    db_preference = db.query(UserIndicatorPreferences).filter(
        UserIndicatorPreferences.id == preference_id
    ).first()
    
    if not db_preference:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Indicator preference not found"
        )
    
    db.delete(db_preference)
    db.commit()


@router.post("/indicators/preferences/bulk", response_model=IndicatorPreferencesListResponse)
async def create_bulk_indicator_preferences(
    preferences: List[IndicatorPreferenceCreate],
    user_id: str = None,
    db: Session = Depends(get_db)
):
    """Create multiple indicator preferences at once"""
    created_preferences = []
    
    for pref in preferences:
        # Skip if already exists
        existing = db.query(UserIndicatorPreferences).filter(
            UserIndicatorPreferences.user_id == user_id,
            UserIndicatorPreferences.indicator_name == pref.indicator_name
        ).first()
        
        if not existing:
            db_preference = UserIndicatorPreferences(
                user_id=user_id,
                **pref.dict()
            )
            db.add(db_preference)
            created_preferences.append(db_preference)
    
    db.commit()
    
    # Refresh all created preferences
    for pref in created_preferences:
        db.refresh(pref)
    
    return {
        "preferences": created_preferences,
        "total": len(created_preferences)
    }