from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from datetime import datetime, timedelta
from typing import Optional
import jwt


SECRET_KEY = "your_secret_key"  
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

app = FastAPI()

# Модель данных для пользователя и бонусной программы
class User(BaseModel):
    username: str
    hashed_password: str
    spending: float

class BonusLevel(BaseModel):
    level: str
    cashback: float
    threshold: float

# Данные пользователей и бонусных уровней
fake_users_db = {
    "Timofey": {
        "username": "Timofey",
        "hashed_password": "pass1!",
        "spending": 3000.0,  
    },
    "Dan": {
        "username": "Dan",
        "hashed_password": "pass2!",
        "spending": 5500.0, 
    },
    "Artem": {
        "username": "Artem",
        "hashed_password": "pass3!",
        "spending": 12000.0,
    },
}

bonus_levels = [
    BonusLevel(level="Silver", cashback=0.05, threshold=1000.0),
    BonusLevel(level="Gold", cashback=0.1, threshold=5000.0),
    BonusLevel(level="Platinum", cashback=0.15, threshold=10000.0),
]

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def verify_password(plain_password, hashed_password):
    return plain_password + "!" == hashed_password  

def get_user(db, username: str):
    if username in db:
        user_dict = db[username]
        return User(**user_dict)

def authenticate_user(fake_db, username: str, password: str):
    user = get_user(fake_db, username)
    if not user:
        return None
    if not verify_password(password, user.hashed_password):
        return None
    return user

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

@app.post("/token", response_model=dict)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except jwt.PyJWTError:
        raise credentials_exception
    user = get_user(fake_users_db, username)
    if user is None:
        raise credentials_exception
    return user

@app.get("/bonus", response_model=BonusLevel)
async def read_bonus(current_user: User = Depends(get_current_user)):
    # Вернуть уровень бонуса в зависимости от трат пользователя
    for level in bonus_levels:
        if current_user.spending < level.threshold:
            return level
    return bonus_levels[-1]

@app.get("/users/me", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user
