# -*- coding: utf-8 -*-
import json

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession
from app.api import Response, pwd_context, get_current_user
from app.config.config import settings
from app.config.const import chat_server, RAGFLOW, workflow_server, DIFY, TMP_DICT, SYSTEM_ID, SYSTEM_STATUS_ON
from app.models import SystemDataModel
from app.models.app_token_model import AppToken
from app.models.base_model import get_db
from app.models.postgresql_base_model import get_pdb
from app.models.token_model import upsert_token
from app.models.user import UserCreate, LoginData
from app.models.user_model import UserModel, UserTokenModel
from app.service.auth import authenticate_user, create_access_token, is_valid_password, save_register_user, password_rsa
from app.service.service_token import  get_token
from app.service.ragflow import RagflowService
from sqlalchemy.future import select


router = APIRouter()


@router.post("/register", response_model=Response)
async def register(user: UserCreate, db=Depends(get_db)):
    db_user = db.query(UserModel).filter(UserModel.username == user.username).first()
    if db_user:
        return Response(code=200, msg="Username already registered")

    # bisheng_service = BishengService(settings.sgb_base_url)
    ragflow_service = RagflowService(settings.fwr_base_url)

    # 注册到毕昇
    # try:
    #     bisheng_info = await bisheng_service.register(user.username, user.password)
    # except Exception as e:
    #     return Response(code=500, msg=f"Failed to register with Bisheng: {str(e)}")

    # 注册到ragflow
    try:
        ragflow_info = await ragflow_service.register(user.username, user.password)
    except Exception as e:
        return Response(code=500, msg=f"Failed to register with Ragflow: {str(e)}")

    # 存储用户信息
    hashed_password = pwd_context.hash(user.password)
    db_user = UserModel(username=user.username, hashed_password=hashed_password, email=ragflow_info.get("email",  f"{user.username}@example.com"),ragflow_id=ragflow_info.get("id"),bisheng_id="")
    db_user.password = db_user.encrypted_password(user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return Response(code=200, msg="User registered successfully",data={"username": db_user.username})


@router.post("/login", response_model=Response)
async def login(login_data: LoginData, db: Session = Depends(get_db)):
    user = authenticate_user(db, login_data.username, login_data.password)
    if not user:
        return Response(code=400, msg="Incorrect username or password")

    # bisheng_service = BishengService(settings.sgb_base_url)
    ragflow_service = RagflowService(settings.fwr_base_url)

    # 登录到毕昇
    # try:
    #     bisheng_token = await bisheng_service.login(login_data.username, login_data.password)
    # except Exception as e:
    #     return Response(code=500, msg=f"Failed to login with Bisheng: {str(e)}")

    # 登录到ragflow
    try:
        ragflow_token = await ragflow_service.login(login_data.username, login_data.password)
    except Exception as e:
        return Response(code=500, msg=f"Failed to login with Ragflow: {str(e)}")

    # 创建本地token
    access_token = create_access_token(data={"sub": user.username, "user_id": user.id})

    upsert_token(db, user.id, access_token, "bisheng_token", ragflow_token)
    # print(111)
    return Response(code=200, msg="Login successful", data={
        "access_token": access_token,
        "token_type": "bearer",
        "username": user.username,
        "nickname": "",
        # "user": user.to_login_json()
    })


@router.get("/token", response_model=Response)
async def token_api(db: Session = Depends(get_db), current_user: UserModel = Depends(get_current_user)):
    # 查询现有记录
    token = await get_token(db, current_user.id)
    if token is None:
        return Response(code=400, msg="token not found")
    return Response(code=200, msg="success", data=token)


@router.post("/v2/login", response_model=Response)
async def login_v2(login_data: LoginData, db: Session = Depends(get_db), pdb: AsyncSession = Depends(get_pdb)):
    password = await password_rsa(login_data.password)
    user = authenticate_user(db, login_data.username, password)
    if not user:
        return Response(code=400, msg="Incorrect username or password")
    """
    app_register = AppRegisterDao(db).get_apps()
    token_dict = {}
    for app in app_register:
        if app["id"] == RAGFLOW:
            service = RagflowService(settings.fwr_base_url)
        elif app["id"] == BISHENG:
            service = BishengService(settings.sgb_base_url)
        elif app["id"] == DIFY:
            service = DifyService(settings.dify_base_url)
        else:
            logger.error("未知注册应用---")
            continue
        try:
            name = login_data.username
            app_password = login_data.password
            user_app = await UserAppDao(db).get_data_by_id(user.id, app["id"])
            if user_app:
                name  = user_app.username
                app_password = user_app.decrypted_password(user_app.password)
            else:
                await update_user_info(db, user.id)
            token = await service.login(name, app_password)
            token_dict[app["id"]] = token
        except Exception as e:
            return Response(code=500, msg=f"Failed to login with {app['id']}: {str(e)}")
    """
    system = db.query(SystemDataModel).filter_by(id=SYSTEM_ID).first()
    if not system or system.status != SYSTEM_STATUS_ON:
        return Response(code=400, msg="系统状态异常，请授权激活后操作！")
    # 创建本地token
    access_token = create_access_token(data={"sub": user.username, "user_id": user.id, "lex": system.expired_at.strftime('%Y-%m-%d %H:%M:%S')})

    # await update_token(db, user.id, access_token, token_dict)
    # await update_user_token(db, user.id, token_dict)
    token_dict = {}
    user_tokens = db.query(UserTokenModel).all()
    for user_token in user_tokens:
        token_dict[TMP_DICT[user_token.id]] = user_token.access_token
    result = await pdb.execute(select(AppToken).where(AppToken.id == user.id))
    db_app_token = result.scalars().first()
    if isinstance(access_token, bytes):
        access_token = access_token.decode()
    if not db_app_token:
        app_token = AppToken(id=user.id, token=access_token, app_token=json.dumps(token_dict))
        pdb.add(app_token)
        await pdb.commit()
        await pdb.refresh(app_token)
    else:
        db_app_token.token = access_token
        db_app_token.app_token = json.dumps(token_dict)
        await pdb.commit()
        await pdb.refresh(db_app_token)

    return Response(code=200, msg="Login successful", data={
        "access_token": access_token,
        "token_type": "bearer",
        "username": user.username,
        "nickname": "",
        # "user": user.to_login_json()
    })



@router.post("/v2/register", response_model=Response)
async def register_v2(user: UserCreate, db=Depends(get_db)):
    if "@" in user.username:
        return Response(code=400, msg="Username cannot contain @")
    password = await password_rsa(user.password)
    if not is_valid_password(password):
        return Response(code=400, msg="The password must be at least 8 and contain both numbers and letters")
    db_user = db.query(UserModel).filter(UserModel.username == user.username).first()
    if db_user:
        return Response(code=200, msg="Username already registered")
    """
    app_register = AppRegisterDao(db).get_apps()
    register_dict = {}
    token = ""
    app_password = await generate_password(10)
    for app in app_register:
        if app["id"] == RAGFLOW:
            service = RagflowService(settings.fwr_base_url)
        elif app["id"] == BISHENG:
            service = BishengService(settings.sgb_base_url)
        elif app["id"] == DIFY:
            admin_user = db.query(UserModel).filter(UserModel.permission == "admin").first()
            token = await get_new_token(db, admin_user.id, DIFY)
            if not token:
                logger.error("用户注册获取dftoken失败！")
                return Response(code=500, msg=f"Failed to register with app")
            service = DifyService(settings.dify_base_url)
        else:
            logger.error("未知注册应用---")
            continue
        try:
            name = app["id"] + str(int(time.time()))
            register_info = await service.register(name, app_password, token)
            # print(register_info)
            register_dict[app['id']] = {"id":register_info.get("id"), "name": name, "email": register_info.get("email")}
        except Exception as e:
            return Response(code=500, msg=f"Failed to register with {app['id']}: {str(e)}")
    """
    user_id = await save_register_user(db, user.username, password, user.email, "", {})
    if not user_id:
        return Response(code=500, msg=f"Failed to register with app")
    return Response(code=200, msg="User registered successfully",data={"userFlag": user_id})


@router.get("/v2/sync", response_model=Response)
async def sync_user_tenant(userFlag: str, db=Depends(get_db)):
    # app_register = AppRegisterDao(db).get_app_by_id(RAGFLOW)
    # if app_register:
    #     is_update = await update_user_group(db, userFlag)
    return Response(code=200, msg="success", data={})