"""
One-time script: set a real password on an existing practitioner user
and ensure bidirectional sharingInfo link with test patient Sarah Johnson.
"""
import os
from bson import ObjectId
from dotenv import load_dotenv
from pymongo import MongoClient
from werkzeug.security import generate_password_hash

load_dotenv(os.path.join(os.path.dirname(__file__), '..', '.env'))

MONGODB_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017')
MONGODB_DB_NAME = os.getenv('MONGODB_DB_NAME', 'hipograf')

client = MongoClient(MONGODB_URI)
db = client[MONGODB_DB_NAME]

TEST_PATIENT_ID = ObjectId('69afe148da3cf2b9dbc4dc1e')  # Sarah Johnson
PRACTITIONER_PASSWORD = 'testpass123'


def main():
    # Find a practitioner user to update
    practitioner = db.users.find_one({'roles': 'practitioner'})
    if not practitioner:
        print('No practitioner users found. Run create_practitioners_and_link.py first.')
        return

    prac_id = practitioner['_id']
    prac_name = practitioner.get('dispName', practitioner.get('username', ''))
    prac_username = practitioner.get('username', '')

    print(f'Updating practitioner: {prac_name} (username: {prac_username}, id: {prac_id})')

    # Set real password hash and fix email if it starts with a dot
    password_hash = generate_password_hash(PRACTITIONER_PASSWORD)
    email = practitioner.get('email', '')
    if email.startswith('.'):
        email = email[1:]
    username = prac_username.lstrip('.')

    db.users.update_one(
        {'_id': prac_id},
        {'$set': {'passwdHash': password_hash, 'email': email, 'username': username}},
    )
    print(f'  Set password to: {PRACTITIONER_PASSWORD}')
    print(f'  Fixed email: {email}, username: {username}')

    # Add test patient to practitioner's sharingInfo (if not already)
    db.users.update_one(
        {'_id': prac_id},
        {'$addToSet': {'sharingInfo': TEST_PATIENT_ID}},
    )
    print(f'  Added patient {TEST_PATIENT_ID} to practitioner sharingInfo')

    # Add practitioner to patient's sharingInfo (if not already)
    db.users.update_one(
        {'_id': TEST_PATIENT_ID},
        {'$addToSet': {'sharingInfo': prac_id}},
    )
    print(f'  Added practitioner {prac_id} to patient sharingInfo')

    # Verify
    updated_prac = db.users.find_one({'_id': prac_id})
    updated_patient = db.users.find_one({'_id': TEST_PATIENT_ID})
    print(f'\nPractitioner sharingInfo: {updated_prac.get("sharingInfo", [])}')
    print(f'Patient sharingInfo: {updated_patient.get("sharingInfo", [])}')
    print(f'\nLogin credentials:')
    print(f'  Username: {prac_username}')
    print(f'  Password: {PRACTITIONER_PASSWORD}')
    print('\nDone!')


if __name__ == '__main__':
    main()
    client.close()
