import argparse
from .utils import all_qualities_str
from .constant import output_dir

def parse_args(args):
    parser = argparse.ArgumentParser(description="Weibo Image Rescue Tool")
    parser.add_argument(
        "-u", "--update-cdn", action="store_true", help="Update CDN information only"
    )
    parser.add_argument(
        "-f", type=str, help="Force update CDN information and rescue image from URL"
    )
    parser.add_argument(
        "--force-update",
        action="store_true",
        help="Force update CDN information before rescuing the positional image URL",
    )
    parser.add_argument(
        "-q",
        type=str,
        default=all_qualities_str(),
        help="Specify qualities to rescue, can be a single value or multiple comma-separated values, e.g., l,ml,m,o,t,ol (default: all qualities)",
    )
    parser.add_argument(
        "-o",
        "--output-dir",
        type=str,
        default=f"./{output_dir}/",
        help="Output directory for rescued image files",
    )
    parser.add_argument(
        "--workers",
        type=int,
        default=20,
        help="Max concurrent requests when probing CDN IPs (default: 20)",
    )
    parser.add_argument(
        "--timeout",
        type=float,
        default=10.0,
        help="Request timeout in seconds (default: 10)",
    )
    parser.add_argument("image_url", nargs="?", type=str, help="Image URL to rescue")
    parsed = parser.parse_args(args)

    if parsed.workers < 1:
        parser.error("--workers must be >= 1")
    if parsed.timeout <= 0:
        parser.error("--timeout must be > 0")
    if parsed.update_cdn and (parsed.f or parsed.image_url):
        parser.error("-u/--update-cdn cannot be used with image URL arguments")
    if parsed.update_cdn and parsed.force_update:
        parser.error("-u/--update-cdn cannot be used with --force-update")
    if parsed.f and parsed.image_url:
        parser.error("Provide URL using either positional image_url or -f, not both")
    if parsed.f and parsed.force_update:
        parser.error("-f already forces update; do not use with --force-update")
    if parsed.force_update and not parsed.image_url:
        parser.error("--force-update requires positional image_url")

    return parsed
