"""One-off script to create the dedicated service account used by the
Hire AI Telegram bot (n8n) to call the TA-ATS API.

Role is RECRUITER (not ADMIN) — the minimum role that satisfies
IsRecruiterOrAdmin / IsCandidateOwnerOrStaff for the endpoints the bot calls
(candidate list/search/create/update, bulk-cv-upload, pipeline applications).

Run once against the target environment, e.g.:
    DJANGO_SETTINGS_MODULE=config.settings.prod python create_hireai_bot_service_account.py
"""
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
django.setup()

from django.contrib.auth import get_user_model
from apps.authentication import mcp_client

User = get_user_model()

BOT_EMAIL = "hireai.bot@indovisionservices.in"
BOT_PASSWORD = "HireAI-Bot#7f3Qz91Lm2"

user, created = User.objects.get_or_create(email=BOT_EMAIL, defaults={
    "username": BOT_EMAIL,
    "role": "RECRUITER",
    "full_name": "Hire AI Bot (Telegram service account)",
    "is_staff": True,
    "is_superuser": False,
})
user.role = "RECRUITER"
user.set_password(BOT_PASSWORD)
user.is_active = True
user.save()

print(f"User created: {BOT_EMAIL}")
print(f"   Created new? {created}")

try:
    user.sync_role_group()
    print("   Synced to RECRUITER group")
except Exception as e:
    print(f"   Role sync failed: {e}")

try:
    result = mcp_client.sync_user(BOT_EMAIL, user.password, user.role)
    print(f"   Synced user to MCP: {result}")
except Exception as e:
    print(f"   MCP sync failed: {e}")
