'''
This module stores config and states
'''
from loguru import logger
from collections import Counter
import os
import sys
import json


is_termux = os.environ.get('TERMUX_APP__PACKAGE_NAME') or os.environ.get('TERMUX_APK_RELEASE')
if is_termux:
    logger.info('Termux detected, checking permissions...')
    logger.info('Prevent killing termux by android, getting wakelock...')
    os.system('termux-wake-lock')
    logger.warning('This can cause battery drain!')
    if (os.environ.get('TERMUX_APP__APK_RELEASE') or os.environ.get('TERMUX_APK_RELEASE')) not in ('F_DROID', 'GITHUB'):
        logger.warning('You use not f-droid/github apk release, it may have problems...')
        logger.warning('F-droid termux release here: https://f-droid.org/en/packages/com.termux/')
        logger.warning('Github termux release here: https://github.com/termux/termux-app/releases')
    if float(os.environ.get('TERMUX_VERSION')[:5]) < 0.118:
        logger.warning('You use old version of termux, highly recommended that you update to v0.118.0 or higher ASAP for various bug fixes, including a critical world-readable vulnerability')
    if os.access('/sdcard', os.W_OK):
        logger.success('permission to write on internal storage allowed')
    else:
        logger.warning('permission denied to write on internal storage')
        logger.info('trying get permission...')
        os.system('termux-setup-storage')
        logger.info('Restart termux [Press CTRL+D or command "exit"]')
        sys.exit(0)

# Название сессии
sessdb = 'tl-ub'
avocado_id = 6333102398
default_directory = ''
default_config_file_path = 'config.json'
treat_as_true = ('true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh')
if is_termux:
    default_directory = '/sdcard/ub4tg'
    os.system(f'mkdir -p {default_directory}')
    default_config_file_path = f'{default_directory}/config.json'
if not os.path.exists(default_config_file_path):
    logger.info('config not found, first launch setup...')
    api_id = int(input('enter api_id from https://my.telegram.org/ : '))
    api_hash = input('enter api_hash from https://my.telegram.org/ : ')
    timezone = input('enter timezone, format is Country/City: ')
    db_pymysql = False
    db_sqlite3 = True
    a_h = input('enable automatic use medkit? [y/n]: ').lower() in treat_as_true
    a_404_patient = input('enable automatic bioeb if victim not found or expired? It will be trigger on "Жертва не найдена" [y/n]: ').lower() in treat_as_true
    automine = input('enable automatic mining of gems? [y/n]: ').lower() in treat_as_true
    new_config = {'api_id': api_id,
                  'api_hash': api_hash,
                  'timezone': timezone,
                  'db_pymysql': db_pymysql,
                  'db_sqlite3': db_sqlite3,
                  'a_h': a_h,
                  'a_404_patient': a_404_patient,
                  'automine': automine}
    with open(default_config_file_path, "w") as configfile:
        json.dump(new_config, configfile, indent=4)

with open(default_config_file_path, "r") as configfile:
    from types import SimpleNamespace
    default_params = {'api_id': '1',
                      'api_hash': 'test',
                      'timezone': 'Etc/UTC',
                      'db_pymysql': False,
                      'db_sqlite3': True,
                      'a_h': True,
                      'a_404_patient': True,
                      'automine': True}
    cnf_dict = json.load(configfile)
    for i in default_params.keys():
        if cnf_dict.get(i) is None:
            default_val = default_params[i]
            cnf_dict[i] = default_val
            logger.warning(f'{i} in config not found, using defalt value {default_val}')
    config = SimpleNamespace(**cnf_dict)
    logger.debug('config loaded')

# Api ID и Api Hash полученные на my.telegram.org
api_id = config.api_id
api_hash = config.api_hash
timezone = config.timezone

db_pymysql = config.db_pymysql
db_sqlite3 = config.db_sqlite3
a_h = config.a_h
a_404_patient = config.a_404_patient


class states:
    auto_bioeb_sleep_interval = (6, 66)  # the default on (re)start
    auto_bioeb_pathogen_threshold = 5  # these pathogens will be saved +- 1
    auto_bioeb_min_interval = (0.666, 3.666)  # for fast leak pathogen
    auto_bioeb_max_interval = (71, 121)  # waiting for more pathogen
    # Default strategy mean: you have 4-5 pathogens when auto bioeb is enabled, pathogen overflow reduced
    auto_bioeb_stop = True
    where_send_check_avocado = None
    last_sent_bioeb = 0  # for measure time between reply avocado and bioeb
    last_reply_bioeb_avocado = 0  # same as above
    avocado_reply_timeout = 3  # increase interval if lag more than this timeout in secs
    automine_enabled = config.automine
    latest_successfull_mine = None
    wait_before_next_mine = None
    stats_medkit = 0
    stats_most_infect_spam_chats = Counter()