#!/usr/bin/env bash
# usaco - manage USACO problems
# Usage:
#   usaco new <name> [io-name] [--url <link>]
#                                Create solving/<name> from template.cpp
#                                (io-name sets freopen filenames, defaults to <name>)
#   usaco run <name>             Build main.cpp and run it (in the problem dir)
#   usaco build <name>           Build main.cpp only
#   usaco done <name>            Move solving/<name> -> solved/<name> and git commit
#   usaco undo <name>            Move solved/ or skipped/<name> -> solving/<name>
#   usaco skip <name>            Move solving/<name> -> skipped/<name>
#   usaco vim <name>             Open the problem's main.cpp in $EDITOR (aliases: edit, e)
#   usaco open <name>            Open the problem's saved URL in a browser
#   usaco list                   List problems by status
#   usaco stats                  Show solve counts and recent activity
#   usaco path <name>            Print the problem's directory (used by the ucd shell helper)
#   usaco clean                  Delete compiled binaries and backups from all problem dirs
#   usaco template <name>        Re-copy template.cpp into the problem as main.cpp (backs up old one)
#
# Names may be unique prefixes: 'usaco e diam' finds diamond-collector.

set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CXXFLAGS=(-O2 -std=c++17 -Wall -Wextra)

usage() { sed -n '2,21p' "$0" | sed 's/^# \{0,1\}//'; exit 1; }

find_problem() {  # echoes dir of problem in solving/, solved/, or skipped/; unique prefix ok
    local name="$1" s d matches=()
    for s in solving solved skipped; do
        if [[ -d "$ROOT/$s/$name" ]]; then echo "$ROOT/$s/$name"; return 0; fi
    done
    for s in solving solved skipped; do
        for d in "$ROOT/$s/$name"*/; do
            [[ -d "$d" ]] && matches+=("${d%/}")
        done
    done
    if [[ ${#matches[@]} -eq 1 ]]; then echo "${matches[0]}"; return 0; fi
    if [[ ${#matches[@]} -gt 1 ]]; then
        echo "Error: '$name' is ambiguous:" >&2
        printf '  %s\n' "${matches[@]#$ROOT/}" >&2
        return 1
    fi
    echo "Error: problem '$name' not found in solving/, solved/, or skipped/" >&2
    return 1
}

build_problem() {  # $1 = problem dir
    g++ "${CXXFLAGS[@]}" "$1/main.cpp" -o "$1/main"
}

cmd="${1:-}"; shift || true
case "$cmd" in
    new)
        [[ $# -ge 1 ]] || usage
        name=""; io=""; url=""
        while [[ $# -gt 0 ]]; do
            case "$1" in
                --url) url="${2:-}"; shift 2 ;;
                *) if [[ -z "$name" ]]; then name="$1"; elif [[ -z "$io" ]]; then io="$1"; fi; shift ;;
            esac
        done
        [[ -n "$name" ]] || usage
        io="${io:-$name}"
        dir="$ROOT/solving/$name"
        if [[ -d "$dir" || -d "$ROOT/solved/$name" || -d "$ROOT/skipped/$name" ]]; then
            echo "Error: '$name' already exists" >&2; exit 1
        fi
        mkdir -p "$dir"
        # insert STDIO("<io>"); at the top of main() so file IO is wired up
        sed "s/^int main() {$/int main() {\n  STDIO(\"$io\");/" "$ROOT/template.cpp" > "$dir/main.cpp"
        touch "$dir/$io.in"
        [[ -n "$url" ]] && echo "$url" > "$dir/.url"
        echo "Created solving/$name (io: $io.in / $io.out)"
        (cd "$dir" && exec ${EDITOR:-nvim} main.cpp)
        ;;
    path)
        [[ $# -ge 1 ]] || usage
        find_problem "$1"
        ;;
    clean)
        for s in solving solved skipped; do
            [[ -d "$ROOT/$s" ]] || continue
            find "$ROOT/$s" -mindepth 2 -maxdepth 2 -type f \
                \( -name main -o -name a.out -o -name '*.bak' \) -print -delete | sed "s|^$ROOT/|removed |"
        done
        ;;
    build)
        [[ $# -ge 1 ]] || usage
        dir="$(find_problem "$1")"
        build_problem "$dir"
        echo "Built $dir/main"
        ;;
    run)
        [[ $# -ge 1 ]] || usage
        dir="$(find_problem "$1")"
        build_problem "$dir"
        # run from inside the dir so freopen finds the .in file
        (cd "$dir" && ./main)
        # show the .out file if the program wrote one
        out="$(ls "$dir"/*.out 2>/dev/null | grep -v '/a\.out$' | head -1 || true)"
        if [[ -n "$out" ]]; then
            echo "── $(basename "$out") ──"
            cat "$out"
        fi
        ;;
    done)
        [[ $# -ge 1 ]] || usage
        name="$1"
        [[ -d "$ROOT/solving/$name" ]] || { echo "Error: solving/$name not found" >&2; exit 1; }
        [[ -d "$ROOT/solved/$name" ]] && { echo "Error: solved/$name already exists" >&2; exit 1; }
        mv "$ROOT/solving/$name" "$ROOT/solved/$name"
        echo "Moved to solved/$name 🎉"
        if git -C "$ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
            git -C "$ROOT" add -A "solved/$name" "solving/$name" 2>/dev/null || true
            git -C "$ROOT" commit -m "Solve $name" >/dev/null && echo "Committed: Solve $name"
        fi
        ;;
    undo)
        [[ $# -ge 1 ]] || usage
        name="$1"; from=""
        for s in solved skipped; do
            [[ -d "$ROOT/$s/$name" ]] && from="$s" && break
        done
        [[ -n "$from" ]] || { echo "Error: '$name' not found in solved/ or skipped/" >&2; exit 1; }
        [[ -d "$ROOT/solving/$name" ]] && { echo "Error: solving/$name already exists" >&2; exit 1; }
        mv "$ROOT/$from/$name" "$ROOT/solving/$name"
        echo "Moved back to solving/$name (was $from)"
        ;;
    skip)
        [[ $# -ge 1 ]] || usage
        name="$1"
        [[ -d "$ROOT/solving/$name" ]] || { echo "Error: solving/$name not found" >&2; exit 1; }
        [[ -d "$ROOT/skipped/$name" ]] && { echo "Error: skipped/$name already exists" >&2; exit 1; }
        mkdir -p "$ROOT/skipped"
        mv "$ROOT/solving/$name" "$ROOT/skipped/$name"
        echo "Moved to skipped/$name (usaco undo $name to bring it back)"
        ;;
    vim|edit|e)
        [[ $# -ge 1 ]] || usage
        dir="$(find_problem "$1")"
        # run from inside the dir so :!./main etc. work and .in files are at hand
        (cd "$dir" && exec ${EDITOR:-nvim} main.cpp)
        ;;
    open)
        [[ $# -ge 1 ]] || usage
        dir="$(find_problem "$1")"
        [[ -f "$dir/.url" ]] || { echo "Error: no URL saved for '$1' (use --url with 'new', or write $dir/.url)" >&2; exit 1; }
        xdg-open "$(cat "$dir/.url")" >/dev/null 2>&1 &
        echo "Opening $(cat "$dir/.url")"
        ;;
    list)
        list_by_mtime() {  # list subdirs of $1 oldest-first by last modification
            [[ -d "$1" ]] || return 0
            for d in "$1"/*/; do
                [[ -d "$d" ]] || continue
                # newest mtime of any file in the problem dir
                printf '%s\t%s\n' "$(find "$d" -type f -printf '%T@\n' | sort -n | tail -1)" "$(basename "$d")"
            done | sort -n | cut -f2 | sed 's/^/  /'
        }
        echo "== Solving =="
        list_by_mtime "$ROOT/solving"
        echo
        echo "== Solved =="
        list_by_mtime "$ROOT/solved"
        if [[ -d "$ROOT/skipped" && -n "$(ls -A "$ROOT/skipped" 2>/dev/null)" ]]; then
            echo
            echo "== Skipped =="
            list_by_mtime "$ROOT/skipped"
        fi
        ;;
    stats)
        count() { [[ -d "$1" ]] && find "$1" -mindepth 1 -maxdepth 1 -type d | wc -l || echo 0; }
        solved=$(count "$ROOT/solved"); solving=$(count "$ROOT/solving"); skipped=$(count "$ROOT/skipped")
        now=$(date +%s); week=0; month=0
        if [[ -d "$ROOT/solved" ]]; then
            for d in "$ROOT/solved"/*/; do
                [[ -d "$d" ]] || continue
                t="$(find "$d" -type f -printf '%T@\n' | sort -n | tail -1 | cut -d. -f1)"
                [[ -z "$t" ]] && continue
                age=$(( now - t ))
                (( age <= 7*86400 )) && week=$((week+1))
                (( age <= 30*86400 )) && month=$((month+1))
            done
        fi
        echo "Solved:   $solved"
        echo "Solving:  $solving"
        echo "Skipped:  $skipped"
        echo
        echo "Solved in last 7 days:  $week"
        echo "Solved in last 30 days: $month"
        ;;
    template)
        [[ $# -ge 1 ]] || usage
        dir="$(find_problem "$1")"
        [[ -f "$dir/main.cpp" ]] && cp "$dir/main.cpp" "$dir/main.cpp.bak" && echo "Backed up old main.cpp -> main.cpp.bak"
        cp "$ROOT/template.cpp" "$dir/main.cpp"
        echo "Refreshed $dir/main.cpp from template"
        ;;
    *) usage ;;
esac
