"""v4 - 最干净的版本,无中文 docstring,纯 ASCII,堡垒机粘贴不会破坏。
"""
import asyncio
import os
import sys
import traceback

os.chdir("/app")
sys.path.insert(0, "/app")

import redis.asyncio as aioredis

print("[DEBUG] REDIS_URL env =", repr(os.environ.get("REDIS_URL")))

try:
    from app.config import settings
    print("[DEBUG] settings.redis_url =", repr(settings.redis_url))
except Exception as e:
    print("[ERROR] import settings:", e)
    traceback.print_exc()
    sys.exit(1)

REDIS_URL = os.environ.get("REDIS_URL") or settings.redis_url
print("[DEBUG] using REDIS_URL =", repr(REDIS_URL))


async def main():
    redis = aioredis.from_url(REDIS_URL, protocol=2, decode_responses=True)
    try:
        await redis.ping()
        print("[DEBUG] redis ping OK")
    except Exception as e:
        print("[ERROR] redis ping failed:", e)
        traceback.print_exc()
        await redis.close()
        sys.exit(2)

    from app.services.token_service import TokenService
    svc = TokenService(redis)
    token = await svc.create_token(
        employee_id="dev-admin-001",
        name="admin",
        roles=["admin"],
        department="IT",
        login_source="prod-cli",
    )
    print("ADMIN_TOKEN=" + token)
    await redis.close()


try:
    asyncio.run(main())
except Exception as e:
    print("[FATAL]", e)
    traceback.print_exc()
    sys.exit(99)
