import argparse

from myst_connector.settings import get_app_float, get_app_int, get_optional_app_value


MINIMUM_PROVIDER_QUALITY = get_app_float('minimum_provider_quality')
COUNTRY = get_optional_app_value('country')
IP_SCORE_LIMIT = get_app_int('ip_score_limit')


def parse_args():
    parser = argparse.ArgumentParser(
        description='Connect to a Mysterium provider with quality and country filters',
    )
    parser.add_argument(
        '--min-quality',
        type=float,
        default=MINIMUM_PROVIDER_QUALITY,
        help='Minimum provider quality score from 0.0 to 3.0 (default: %(default)s)'
    )
    parser.add_argument(
        '--country',
        type=str,
        default=COUNTRY,
        help='Optional country filter (for example: US, DE)'
    )
    parser.add_argument(
        '--provider',
        type=str,
        default=None,
        help='Explicit provider ID to try first; falls back to other providers if connection fails'
    )
    parser.add_argument(
        '--ip-score',
        type=int,
        default=IP_SCORE_LIMIT,
        help='Maximum acceptable IP score (default: %(default)s)'
    )
    args = parser.parse_args()

    if not 0.0 <= args.min_quality <= 3.0:
        parser.error('--min-quality must be between 0.0 and 3.0')
    if args.ip_score < 0:
        parser.error('--ip-score must be >= 0')

    args.country = args.country.strip().upper() if args.country else None
    return args
