"""微信扫码登录 OAuth 端点（第一版已注释，待后续启用）"""

# import uuid as _uuid
# from datetime import datetime
# from urllib.parse import urlencode
#
# from fastapi import APIRouter, Depends, HTTPException
# from pydantic import BaseModel
# from sqlalchemy import select
# from sqlalchemy.ext.asyncio import AsyncSession
#
# from app.compat import UTC
# from app.config import settings
# from app.core.cache import cache
# from app.core.permissions import get_current_user
# from app.core.security import create_access_token, create_refresh_token
# from app.core.token_store import token_store
# from app.db import get_db
# from app.models.user import Tenant, User, UserTenant
# from app.schemas.auth import AuthResponse, TenantInfo, TokenResponse, UserProfile
# from app.services.wechat_oauth import (
#     exchange_code_for_token,
#     get_authorize_url,
#     get_user_info,
#     is_dev_mode,
#     make_synthetic_email,
# )
#
# router = APIRouter()
# WECHAT_STATE_PREFIX = "wechat_state:"
#
#
# @router.get("/wechat/authorize", summary="获取微信扫码授权 URL")
# async def wechat_authorize():
#     state = _uuid.uuid4().hex
#     await cache.set(f"{WECHAT_STATE_PREFIX}{state}", {"created_at": datetime.now(UTC).isoformat()}, ttl=600)
#     authorize_url = get_authorize_url(state)
#     return {"authorization_url": authorize_url, "state": state}
#
#
# @router.get("/wechat/callback", summary="微信 OAuth 回调")
# async def wechat_callback(code: str, state: str, db: AsyncSession = Depends(get_db)):
#     st = await cache.pop(f"{WECHAT_STATE_PREFIX}{state}")
#     if not st:
#         raise HTTPException(status_code=400, detail="Invalid or expired state")
#
#     try:
#         token_data = await exchange_code_for_token(code)
#         openid = token_data["openid"]
#         user_info = await get_user_info(token_data["access_token"], openid)
#     except ValueError as e:
#         raise HTTPException(status_code=400, detail=str(e))
#
#     nickname = user_info.get("nickname", "微信用户")
#     avatar = user_info.get("headimgurl", "")
#
#     # 查已有用户
#     result = await db.execute(
#         select(User).where(User.sso_provider == "wechat", User.sso_subject_id == openid)
#     )
#     user = result.scalar()
#
#     if not user:
#         # 自动注册
#         synthetic_email = make_synthetic_email(openid)
#         user = User(
#             email=synthetic_email,
#             hashed_password=None,
#             display_name=nickname,
#             avatar_url=avatar,
#             sso_provider="wechat",
#             sso_subject_id=openid,
#         )
#         db.add(user)
#         await db.flush()
#
#         slug = f"user-{user.id.hex[:12]}"
#         tenant = Tenant(name=f"{nickname}的个人空间", slug=slug)
#         db.add(tenant)
#         await db.flush()
#
#         db.add(UserTenant(user_id=user.id, tenant_id=tenant.id, role="owner", is_default=True))
#         user.last_login_at = datetime.now(UTC)
#         await db.commit()
#         await db.refresh(user)
#         await db.refresh(tenant)
#         default_tenant_id = str(tenant.id)
#         default_role = "owner"
#         tenants_data = [TenantInfo(id=str(tenant.id), name=tenant.name, slug=tenant.slug, plan_type=tenant.plan_type, role="owner")]
#     else:
#         # 已有用户，登录
#         if not user.is_active:
#             raise HTTPException(status_code=403, detail="Account disabled")
#         ut_result = await db.execute(
#             select(UserTenant, Tenant).join(Tenant).where(UserTenant.user_id == user.id)
#         )
#         tenants_data = []
#         default_tenant_id, default_role = None, "viewer"
#         for ut, t in ut_result:
#             tenants_data.append(TenantInfo(id=str(t.id), name=t.name, slug=t.slug, plan_type=t.plan_type, role=ut.role))
#             if ut.is_default:
#                 default_tenant_id, default_role = str(t.id), ut.role
#         if not default_tenant_id and tenants_data:
#             default_tenant_id, default_role = tenants_data[0].id, tenants_data[0].role
#         # 更新昵称和头像
#         if nickname and nickname != "微信用户":
#             user.display_name = nickname
#         if avatar:
#             user.avatar_url = avatar
#         user.last_login_at = datetime.now(UTC)
#         await db.commit()
#
#     access_token = create_access_token(str(user.id), default_tenant_id or "", default_role, is_superuser=user.is_superuser)
#     refresh_token, refresh_jti = create_refresh_token(str(user.id), default_tenant_id or "", default_role, is_superuser=user.is_superuser)
#     await token_store.store_refresh(refresh_jti, str(user.id), default_tenant_id or "")
#
#     # 重定向到前端
#     params = urlencode({
#         "access_token": access_token,
#         "refresh_token": refresh_token,
#         "user_id": str(user.id),
#     })
#     redirect_url = f"{settings.PUBLIC_BASE_URL}/auth/wechat-login-callback?{params}"
#     from fastapi.responses import RedirectResponse
#     return RedirectResponse(url=redirect_url)
#
#
# @router.get("/wechat/user", summary="当前用户微信绑定信息")
# async def wechat_user_info(user: dict = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
#     u = (await db.execute(select(User).where(User.id == _uuid.UUID(user["sub"])))).scalar()
#     if not u:
#         raise HTTPException(404)
#     return {
#         "sso_provider": u.sso_provider,
#         "sso_subject_id": u.sso_subject_id,
#         "wechat_nickname": u.display_name if u.sso_provider == "wechat" else None,
#     }
#
#
# class UnbindRequest(BaseModel):
#     confirm: bool = True
#
#
# @router.post("/wechat/unbind", summary="解绑微信")
# async def wechat_unbind(
#     req: UnbindRequest,
#     user: dict = Depends(get_current_user),
#     db: AsyncSession = Depends(get_db),
# ):
#     if not req.confirm:
#         raise HTTPException(status_code=400, detail="Must confirm unbind")
#     u = (await db.execute(select(User).where(User.id == _uuid.UUID(user["sub"])))).scalar()
#     if not u:
#         raise HTTPException(404)
#     if u.sso_provider != "wechat":
#         raise HTTPException(status_code=400, detail="No WeChat binding found")
#     # 必须有密码或其他登录方式
#     if not u.hashed_password:
#         raise HTTPException(status_code=400, detail="Cannot unbind: no password set. Set a password first.")
#     u.sso_provider = None
#     u.sso_subject_id = None
#     await db.commit()
#     return {"status": "unbound"}
