#compdef satori.problems satori.download-statement satori.download_statement satori.submit satori.passwd satori.login satori.change_contest satori.console

_satori_problem_codes() {
    local cache_dir="${HOME}/.cache/satori"
    [[ -d "$cache_dir" ]] || return 0
    local -a items
    local line
    while IFS= read -r line; do
        [[ -n "$line" ]] && items+=("$line")
    done < <(python3 -c '
import glob, json, os
for p in sorted(glob.glob(os.path.expanduser("~/.cache/satori/contest_*_problems.json"))):
    try:
        with open(p) as f:
            data = json.load(f)
        for pm in data.get("problems", []):
            code = pm.get("code", "")
            title = pm.get("title", "").replace(":", "\\:")
            if code:
                print("%s:%s" % (code, title))
    except Exception:
        pass
' 2>/dev/null)
    if (( ${#items} )); then
        _describe -t problems 'problem code' items
    fi
}

_satori_submit_ids() {
    local cache_dir="${HOME}/.cache/satori"
    [[ -d "$cache_dir" ]] || return 0
    local -a items
    local line
    while IFS= read -r line; do
        [[ -n "$line" ]] && items+=("$line")
    done < <(python3 -c '
import glob, json, os
for p in sorted(glob.glob(os.path.expanduser("~/.cache/satori/contest_*_results.json"))):
    try:
        with open(p) as f:
            data = json.load(f)
        for r in data.get("results", [])[:30]:
            sid = r.get("id")
            code = r.get("code", "")
            status = r.get("status", "")
            if sid is not None:
                print("%s:%s (%s)" % (sid, code, status))
    except Exception:
        pass
' 2>/dev/null)
    if (( ${#items} )); then
        _describe -t submits 'submit ID' items
    fi
}

_satori_common_opts() {
    _arguments -s \
        '(-h --help)'{-h,--help}'[Show help message]' \
        '(-c --config)'{-c,--config}'[Config file]:file:_files' \
        '(-s --section)'{-s,--section}'[Config section]:section:' \
        '(-H --host)'{-H,--host}'[Satori host:port:blobport]:host:' \
        '(-u --username)'{-u,--username}'[Username]:username:' \
        '(-p --password)'{-p,--password}'[Password]:password:' \
        '(-m --machine)'{-m,--machine}'[Machine name]:machine:' \
        '(-S --ssl)'{-S,--ssl}'[Use SSL]' \
        '(-l --loglevel)'{-l,--loglevel}'[Log level]:level:(DEBUG INFO WARNING ERROR CRITICAL)'
}

_satori_problems() {
    local context state state_descr line
    typeset -A opt_args

    local -a subcmds
    subcmds=(
        'list:List problems in the contest'
        'status:Show solved/unsolved status for all problems'
        'statement:Show or download a problem statement'
        'download-statement:Download problem statement(s) as PDF'
        'downloadstatement:Alias for download-statement'
        'results:List recent submissions'
        'result:Show test report for a submission'
        'downloadsubmit:Download source code of a submission'
        'dispatchers:List available dispatchers'
        'reporters:List available reporters'
        'reporter:Show parameters for a reporter'
        'download:Download full problem package (admins/authors)'
        'test:Run local tests via TemporarySubmit'
        'testresult:Show TemporarySubmit result'
        'upload:Upload problem package (admins/authors)'
        'render:Render statement to PDF (admins/authors)'
    )

    _arguments -C \
        '(-h --help)'{-h,--help}'[Show help message]' \
        '(-c --config)'{-c,--config}'[Config file]:file:_files' \
        '(-s --section)'{-s,--section}'[Config section]:section:' \
        '(-H --host)'{-H,--host}'[Satori host]:host:' \
        '(-u --username)'{-u,--username}'[Username]:username:' \
        '(-p --password)'{-p,--password}'[Password]:password:' \
        '(-m --machine)'{-m,--machine}'[Machine name]:machine:' \
        '(-S --ssl)'{-S,--ssl}'[Use SSL]' \
        '(-l --loglevel)'{-l,--loglevel}'[Log level]:level:(DEBUG INFO WARNING ERROR CRITICAL)' \
        '1: :->subcmd' \
        '*::arg:->args'

    case "$state" in
        subcmd)
            _describe -t subcommands 'satori.problems command' subcmds
            ;;
        args)
            case "${line[1]}" in
                list)
                    _arguments -s \
                        '(-s --status)'{-s,--status}'[Show completion status]' \
                        '(-r --refresh)'{-r,--refresh}'[Force refresh from server]' \
                        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
                        '(-h --help)'{-h,--help}'[Show help]'
                    ;;
                status)
                    _arguments -s \
                        '(-r --refresh)'{-r,--refresh}'[Force refresh from server]' \
                        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
                        '(-h --help)'{-h,--help}'[Show help]'
                    ;;
                statement)
                    _arguments -s \
                        '(-r --refresh)'{-r,--refresh}'[Force refresh from server]' \
                        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
                        '--pdf[Download statement as PDF]' \
                        '(-o --output)'{-o,--output}'[Output PDF filename]:file:_files' \
                        '(-h --help)'{-h,--help}'[Show help]' \
                        '1:problem code:_satori_problem_codes'
                    ;;
                download-statement|downloadstatement)
                    _arguments -s \
                        '(-a --all)'{-a,--all}'[Download all PDF statements]' \
                        '(-o --output)'{-o,--output}'[Output PDF filename (single problem)]:file:_files' \
                        '(-d --dir)'{-d,--dir}'[Output directory]:directory:_files -/' \
                        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
                        '(-h --help)'{-h,--help}'[Show help]' \
                        '*:problem code:_satori_problem_codes'
                    ;;
                results)
                    _arguments -s \
                        '(-n --limit)'{-n,--limit}'[Number of submits per page]:limit:' \
                        '(-P --page)'{-P,--page}'[Page number]:page:' \
                        '(-a --all)'{-a,--all}'[Show all submits]' \
                        '(-r --refresh)'{-r,--refresh}'[Force refresh from server]' \
                        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
                        '(-h --help)'{-h,--help}'[Show help]'
                    ;;
                result|downloadsubmit)
                    _arguments -s \
                        '(-r --refresh)'{-r,--refresh}'[Force refresh from server]' \
                        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
                        '(-h --help)'{-h,--help}'[Show help]' \
                        '1:submit id:_satori_submit_ids'
                    ;;
                test)
                    _arguments -s \
                        '(-2 --results2d)'{-2,--results2d}'[Show 2D results table]' \
                        '(-t --time)'{-t,--time}'[Override time limit]:time:' \
                        '(-v --verbose)'{-v,--verbose}'[Verbose output]' \
                        '(-o --override)'{-o,--override}'[Override test data]:override:' \
                        '--store_io[Store input/output]' \
                        '(-h --help)'{-h,--help}'[Show help]' \
                        '*:file:_files'
                    ;;
                upload|render)
                    _files
                    ;;
            esac
            ;;
    esac
}

_satori_download_statement_zsh() {
    _arguments -s \
        '(-a --all)'{-a,--all}'[Download all PDF statements]' \
        '(-o --output)'{-o,--output}'[Output PDF filename (single problem)]:file:_files' \
        '(-d --dir)'{-d,--dir}'[Output directory]:directory:_files -/' \
        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
        '(-h --help)'{-h,--help}'[Show help]' \
        '*:problem code:_satori_problem_codes'
}

_satori_submit_zsh() {
    _arguments -s \
        '(-C --contest)'{-C,--contest}'[Contest ID]:contest id:' \
        '(-W --no-wait)'{-W,--no-wait}'[Do not wait for test results]' \
        '(-t --timeout)'{-t,--timeout}'[Max wait time in seconds]:seconds:' \
        '(-h --help)'{-h,--help}'[Show help]' \
        '1:problem code:_satori_problem_codes' \
        '2:solution file:_files'
}

case "$service" in
    satori.problems)
        _satori_problems "$@"
        ;;
    satori.download-statement|satori.download_statement)
        _satori_download_statement_zsh "$@"
        ;;
    satori.submit)
        _satori_submit_zsh "$@"
        ;;
    *)
        _satori_common_opts "$@"
        ;;
esac
