"""创建 / 重置一个 admin 后台账号。

用法(在项目根、已 pip install -e . 的环境里跑):
  python scripts/create_admin.py --username admin --role super_admin
      不传 --password → 自动生成强随机密码,打印一次,务必当场保存
  python scripts/create_admin.py --username ops --role operator --password 'xxx'

幂等:username 已存在则重置其密码 + 角色 + 置为 active(忘记密码时用它重置)。
角色:super_admin(全权+管账号)/ finance(钱)/ operator(用户+反馈+大盘)。
"""
from __future__ import annotations

import argparse
import secrets

from app.admin.repositories import admin_user as admin_repo
from app.core.security import hash_password
from app.db.session import SessionLocal

_ROLES = ("super_admin", "finance", "operator")


def main() -> None:
    parser = argparse.ArgumentParser(description="创建或重置 admin 账号")
    parser.add_argument("--username", required=True)
    parser.add_argument("--role", default="super_admin", choices=_ROLES)
    parser.add_argument("--password", default=None, help="不传则自动生成强随机密码")
    args = parser.parse_args()

    password = args.password or secrets.token_urlsafe(16)
    generated = args.password is None

    db = SessionLocal()
    try:
        existing = admin_repo.get_by_username(db, args.username)
        if existing is None:
            admin = admin_repo.create_admin(
                db, username=args.username, password=password, role=args.role
            )
            action = "创建"
        else:
            existing.password_hash = hash_password(password)
            existing.role = args.role
            existing.status = "active"
            db.commit()
            db.refresh(existing)
            admin = existing
            action = "重置"
    finally:
        db.close()

    print(f"✅ 已{action} admin: id={admin.id} username={admin.username} role={admin.role}")
    if generated:
        print(f"🔑 自动生成的密码(只显示这一次,请立即保存):\n   {password}")


if __name__ == "__main__":
    main()
