"""
é¢�å¤–ä¾�èµ–pip install nonebot_plugin_apscheduler
å®šæ—¶æ�¨é€�ç¾¤æ¶ˆæ�¯éœ€è¦�åœ¨.evnä¸­é…�ç½®:
send_group_id = ["xxx", "xxx"]                    # å¿…å¡« ç¾¤å�·
send_switch_morning = False                       # é€‰å¡« True/False é»˜è®¤å¼€å�¯ æ—©ä¸Šæ¶ˆæ�¯æ�¨é€�æ˜¯å�¦å¼€å�¯
send_switch_night = False                         # é€‰å¡« True/False é»˜è®¤å¼€å�¯ æ™šä¸Šæ¶ˆæ�¯æ�¨é€�æ˜¯å�¦å¼€å�¯
send_mode = 1                                     # é€‰å¡« é»˜è®¤æ¨¡å¼�2 æ¨¡å¼�1å�‘é€�è‡ªå®šä¹‰å�¥å­�ï¼Œæ¨¡å¼�2éš�æœºè°ƒç”¨ä¸€å�¥
send_sentence_morning = ["å�¥å­�1", "å�¥å­�2", "..."]  # å¦‚æ�œæ˜¯æ¨¡å¼�1 æ­¤é¡¹å¿…å¡«ï¼Œæ—©ä¸Šéš�æœºå�‘é€�è¯¥å­—æ®µä¸­çš„ä¸€å�¥
send_sentence_night = ["å�¥å­�1", "å�¥å­�2", "..."]   # å¦‚æ�œæ˜¯æ¨¡å¼�1 æ­¤é¡¹å¿…å¡«ï¼Œæ™šä¸Šéš�æœºå�‘é€�è¯¥å­—æ®µä¸­çš„ä¸€å�¥
send_time_morning = "8 0"                          # é€‰å¡« æ—©ä¸Šå�‘é€�æ—¶é—´é»˜è®¤ä¸º7:00
send_time_night = "23 0"                          # é€‰å¡« æ™šä¸Šå�‘é€�æ—¶é—´é»˜è®¤ä¸º22:00              
"""
# FIXME æ­¤åŠŸèƒ½ä¸ºç”¨æˆ·PRï¼Œç›®å‰�å…ˆç”¨é…�ç½®å½¢å¼�ï¼Œå��ç»­ä¿®æ”¹ä¸ºåŠ¨æ€�é…�ç½®
import asyncio
import json
import random

import requests
from nonebot import require, get_bots, get_driver
from nonebot.log import logger
from nonebot.plugin import get_available_plugin_names

from .func_hook import check_func_status

# è�·å�–QQç¾¤å�·
try:
    send_group_id = get_driver().config.send_group_id  # <-å¡«å†™éœ€è¦�æ”¶å�‘çš„QQç¾¤å�·,åˆ©ç”¨forå¾ªç�¯é��å�†å�‘é€�
except Exception as e:
    logger.error("ValueError:{}", e)
    logger.error('è¯·é…�ç½®send_group_id')

# å¼€å…³ é»˜è®¤å…¨å¼€
try:
    send_switch_morning = get_driver().config.send_switch_morning
except(AttributeError, AssertionError):
    send_switch_morning = True
try:
    send_switch_night = get_driver().config.send_switch_night
except(AttributeError, AssertionError):
    send_switch_night = True
# print(send_switch_morning)
# print(not send_switch_morning)
# print(type(send_switch_morning))
# evnè¯»è¿›æ�¥æ˜¯strç±»å�‹ï¼Œå��äº†å•Šï¼Œè¿™ä¸ªbugæ‰¾äº†å¥½ä¹…ä¸€ç›´ä»¥ä¸ºæ˜¯é€»è¾‘æœ‰é”™ã€‚strè½¬bool
send_switch_morning = bool(send_switch_morning)
send_switch_night = bool(send_switch_night)

# è�·å�–æ¨¡å¼� é»˜è®¤æ¨¡å¼�2 å¦‚æ�œæ˜¯æ¨¡å¼�1å°±è¯»å�–è‡ªå®šä¹‰å�¥å­�ï¼Œæ¨¡å¼�2ä½¿ç”¨API
try:
    send_mode = get_driver().config.send_mode
except(AttributeError, AssertionError):
    send_mode = 2
if send_mode == 1:
    send_sentence_morning = get_driver().config.send_sentence_morning
    send_sentence_night = get_driver().config.send_sentence_night

# è�·å�–è‡ªå®šä¹‰æ—¶é—´ï¼Œé»˜è®¤æ—©ä¸Šä¸ƒç‚¹ï¼Œæ™šä¸Šå��ç‚¹
try:
    send_time_morning = get_driver().config.send_time_morning
    send_time_night = get_driver().config.send_time_night
    assert send_time_morning is not None
except(AttributeError, AssertionError):
    send_time_morning = '7 0'
    send_time_night = '22 0'
m_hour, m_minute = send_time_morning.split(' ')
n_hour, n_minute = send_time_night.split(' ')

# éš�æœºä¸€è¨€API
def hitokoto():
    url = "https://v1.hitokoto.cn?c=a&c=b&c=c&c=d&c=h"
    txt = requests.get(url)
    data = json.loads(txt.text)
    msg = data['hitokoto']
    add = ""
    if works := data['from']:
        add += f"ã€Š{works}ã€‹"
    if from_who := data['from_who']:
        add += f"{from_who}"
    if add:
        msg += f"\nâ€”â€”{add}"
    return msg

async def send_morning():
    # å¦‚æ�œFalseç›´æ�¥é€€å‡ºå‡½æ•°
    if not send_switch_morning:
        logger.info('send_morning()å…³é—­ï¼Œè·³å‡ºå‡½æ•°')
        return
    sendSuccess = False
    while not sendSuccess:
        try:
            await asyncio.sleep(random.randint(1, 10))
            # await get_bot().send_private_msg(user_id = fire_user_id, message = "ğŸŒ�æ—©ï¼Œå�ˆæ˜¯å…ƒæ°”æ»¡æ»¡çš„ä¸€å¤©")  #
            # å½“æœªè¿�æ�¥åˆ°onebot.v11å��è®®ç«¯æ—¶ä¼šæŠ›å‡ºå¼‚å¸¸
            bots = get_bots()
            for bot in bots.values():
                for gid in send_group_id:
                    if await check_func_status('group_msg', gid):
                        if send_mode == 1:
                            try:
                                await bot.send_group_msg(group_id=gid,
                                                         message=f"{random.choice(send_sentence_morning)}")
                            except Exception:
                                # è¿™ä¸ªæœºå™¨äººæ²¡æœ‰åŠ è¿™ä¸ªç¾¤
                                pass
                        if send_mode == 2:
                            try:
                                await bot.send_group_msg(group_id=gid, message=hitokoto())
                            except Exception:
                                # è¿™ä¸ªæœºå™¨äººæ²¡æœ‰åŠ è¿™ä¸ªç¾¤
                                pass
                logger.info('ç¾¤è�Šæ�¨é€�æ¶ˆæ�¯')
                sendSuccess = True
        except ValueError as E:
            logger.error("ValueError:{}", E)
            logger.error('ç¾¤è�Šæ�¨é€�æ¶ˆæ�¯æ�’ä»¶è�·å�–botå¤±è´¥ï¼Œ1så��é‡�è¯•')
            await asyncio.sleep(1)  # é‡�è¯•å‰�æ—¶å»¶ï¼Œé˜²æ­¢é˜»å¡�

async def send_night():
    # å¦‚æ�œFalseç›´æ�¥é€€å‡ºå‡½æ•°
    if not send_switch_night:
        logger.info('send_night()å…³é—­ï¼Œè·³å‡ºå‡½æ•°')
        return
    sendSuccess = False
    while not sendSuccess:
        try:
            await asyncio.sleep(random.randint(1, 10))
            # await get_bot().send_private_msg(user_id = fire_user_id, message = "ğŸŒ›ä»Šå¤©ç»­ç�«èŠ±äº†ä¹ˆï¼Œæ™šå®‰å•¦")  #
            # å½“æœªè¿�æ�¥åˆ°onebot.v11å��è®®ç«¯æ—¶ä¼šæŠ›å‡ºå¼‚å¸¸
            bots = get_bots()
            for bot in bots.values():
                for gid in send_group_id:
                    if await check_func_status('group_msg', gid):
                        if send_mode == 1:
                            try:
                                await bot.send_group_msg(group_id=gid, message=f"{random.choice(send_sentence_night)}")
                            except Exception:
                                # è¿™ä¸ªæœºå™¨äººæ²¡æœ‰åŠ è¿™ä¸ªç¾¤
                                pass
                        if send_mode == 2:
                            try:
                                await bot.send_group_msg(group_id=gid, message=hitokoto())
                            except Exception:
                                # è¿™ä¸ªæœºå™¨äººæ²¡æœ‰åŠ è¿™ä¸ªç¾¤
                                pass
                logger.info('ç¾¤è�Šæ�¨é€�æ¶ˆæ�¯')
                sendSuccess = True
        except ValueError as E:
            logger.error("ValueError:{}", E)
            logger.error('ç¾¤è�Šæ�¨é€�æ¶ˆæ�¯æ�’ä»¶è�·å�–botå¤±è´¥ï¼Œ1så��é‡�è¯•')
            await asyncio.sleep(1)  # é‡�è¯•å‰�æ—¶å»¶ï¼Œé˜²æ­¢é˜»å¡�

try:
    assert 'nonebot_plugin_apscheduler' in get_available_plugin_names()
    require('nonebot_plugin_apscheduler')
    from nonebot_plugin_apscheduler import scheduler
    logger.info('å·²æ£€æµ‹åˆ°è½¯ä¾�èµ–nonebot_plugin_apschedulerï¼Œå¼€å�¯å®šæ—¶ä»»åŠ¡åŠŸèƒ½')
    scheduler.add_job(send_morning, 'cron', hour=m_hour, minute=m_minute, id='send_morning')  # æ—©ä¸Šæ�¨é€�
    scheduler.add_job(send_night, 'cron', hour=n_hour, minute=n_minute, id='send_night')  # æ™šä¸Šæ�¨é€�
except:
    logger.error('æœªæ£€æµ‹åˆ°è½¯ä¾�èµ–nonebot_plugin_apschedulerï¼Œç¦�ç”¨å®šæ—¶ä»»åŠ¡åŠŸèƒ½')
