#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8

"""
Agent在和用户对话过程中可能识别到用户不想再收消息，Agent会做识别，但需将信息同步至Growth Manager
"""

import json
import pymysql.cursors

from pqai_agent import configs
from pqai_agent.user_manager import MySQLUserManager, MySQLUserRelationManager

if __name__ == '__main__':
    config = configs.get()
    user_db_config = config['storage']['user']
    staff_db_config = config['storage']['staff']
    user_manager = MySQLUserManager(user_db_config['mysql'], user_db_config['table'], staff_db_config['table'])
    wecom_db_config = config['storage']['user_relation']
    user_relation_manager = MySQLUserRelationManager(
        user_db_config['mysql'], wecom_db_config['mysql'],
        config['storage']['staff']['table'],
        user_db_config['table'],
        wecom_db_config['table']['staff'],
        wecom_db_config['table']['relation'],
        wecom_db_config['table']['user']
    )

    sql = f"SELECT wxid, name, profile_data_v1 FROM {user_manager.table_name} WHERE profile_data_v1 IS NOT NULL"
    users = user_manager.db.select(sql, pymysql.cursors.DictCursor)
    for user in users:
        profile = json.loads(user['profile_data_v1'])
        if profile.get('interaction_frequency', None) == 'stopped':
            user_id = user['wxid']
            user_name = user['name']
            print(f'update user[{user_id}] {user_name}: stop group message')
            sql = f"UPDATE we_com_user SET group_msg_disabled = 1 WHERE union_id = %s"
            rows = user_relation_manager.wecom_db.execute(sql, (user_id, ))
            print(f'affected rows: {rows}')

