#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
# Vishow abridged IPQuality interface: Sections 1–5 only.
# Python handles bounded requests and structured parsing; Bash renders the report.
# No root requirement, installers, counters, advertisements, mail tests or uploads.

script_dir=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) || exit 1
json_mode=0
arguments=()

usage() {
    printf '%s\n' 'Vishow local IP checker — 0.1.0 draft' \
      'Usage: ./check.sh [--json] [--ipv4|--ipv6] [--services all|ai|media|none]' \
      '       ./check.sh --ip PUBLIC_IP --services none [--json]' \
      '' 'Run on the device or VPS whose connection you want to check.' \
      'IPINFO_TOKEN enables basic information. Other providers need their own keys.' \
      'VISHOW_PROXY optionally specifies an explicit HTTP(S) or SOCKS proxy.' \
      'Default: IPv4, all listed services. Results are never uploaded.' \
      'A web response does not establish account access or successful chat/playback.'
}

while (( $# )); do
    case "$1" in
        --help|-h) usage; exit 0 ;;
        --json) json_mode=1; shift ;;
        --ipv4) arguments+=(--family 4); shift ;;
        --ipv6) arguments+=(--family 6); shift ;;
        --ip|--services)
            if (( $# < 2 )); then printf 'Missing argument for %s\n' "$1" >&2; exit 2; fi
            arguments+=("$1" "$2"); shift 2 ;;
        *) printf 'Unknown option: %s\n' "$1" >&2; usage >&2; exit 2 ;;
    esac
done
for dependency in python3 curl jq; do
    if ! command -v "$dependency" >/dev/null 2>&1; then
        printf 'Required command is missing: %s. No changes were made.\n' "$dependency" >&2
        exit 2
    fi
done

report=$(python3 "$script_dir/backend/diagnostics.py" "${arguments[@]}")
result=$?
if ! printf '%s' "$report" | jq -e '.schema_version == 1' >/dev/null 2>&1; then
    printf '%s\n' 'No valid report was produced.' >&2
    exit 2
fi
if (( json_mode )); then
    printf '%s\n' "$report"
    exit "$result"
fi

read_field() { printf '%s' "$report" | jq -r "$1"; }
show_basic() {
    printf '\n1. Basic Information (IPinfo Lite)\n'
    read_field '.basic | to_entries[] | [.key, (.value // "Unknown")] | @tsv' |
      while IFS=$'\t' read -r key value; do printf '  %-18s %s\n' "$key" "$value"; done
    printf '  %-18s %s\n' 'Provider status' "$(read_field '.basic_status')"
}
show_type() {
    printf '\n2. IP Type\n  %-14s %-18s %-18s %s\n' 'Database' 'Usage' 'Company' 'Source status'
    read_field '.providers[] | select(.id == "ipinfo" or .id == "ipregistry" or .id == "ipapi" or .id == "ip2location" or .id == "abuseipdb") | [.name, (.usage // "Unknown"), (.company // "Unknown"), .status] | @tsv' |
      while IFS=$'\t' read -r name usage company status; do
          printf '  %-14s %-18s %-18s %s\n' "$name" "$usage" "$company" "$status"
      done
}
show_score() {
    printf '\n3. Risk Scores (separate provider scales)\n'
    read_field '.providers[] | select(.id == "ip2location" or .id == "scamalytics" or .id == "ipapi" or .id == "abuseipdb" or .id == "ipqs" or .id == "dbip") | [.name, (if .score == null then "Unknown" elif .score.unit == "category" then "Category" elif .score.unit == "percent" then ((.score.value|tostring) + "%") else ((.score.value|tostring)+" / "+(.score.maximum|tostring)) end), (.score.risk // "Unknown"), .status] | @tsv' |
      while IFS=$'\t' read -r name score risk status; do
          printf '  %-14s %-14s %-14s %s\n' "$name" "$score" "$risk" "$status"
      done
}
show_factor() {
    printf '\n4. Risk Factors\n  %-14s %-7s %-7s %-7s %-7s %-7s %-7s %-7s\n' 'Database' 'Region' 'Proxy' 'Tor' 'VPN' 'Server' 'Abuser' 'Robot'
    read_field 'def flag: if . == true then "Yes" elif . == false then "No" else "N/A" end; .providers[] | [.name, (.region // "N/A"), (.flags.proxy|flag), (.flags.tor|flag), (.flags.vpn|flag), (.flags.server|flag), (.flags.abuser|flag), (.flags.robot|flag)] | @tsv' |
      while IFS=$'\t' read -r name region proxy tor vpn server abuser robot; do
          printf '  %-14s %-7s %-7s %-7s %-7s %-7s %-7s %-7s\n' "$name" "$region" "$proxy" "$tor" "$vpn" "$server" "$abuser" "$robot"
      done
}
show_media() {
    printf '\n5. Media and AI Services\n'
    if [[ $(read_field '.services | length') == 0 ]]; then
        printf '  Not requested. An arbitrary remote IP cannot be service-tested.\n'
        return
    fi
    read_field '.services[] | [.name, .status, (.http_status // "—" | tostring), .evidence] | @tsv' |
      while IFS=$'\t' read -r name status http evidence; do
          printf '  %-19s %-18s HTTP %-3s %s\n' "$name" "$status" "$http" "$evidence"
      done
    read_field '.services[] | .name as $service | (.probes // [])[] | [$service, .label, .status, .evidence] | @tsv' |
      while IFS=$'\t' read -r name label status evidence; do
          printf '    %s / %s: %s — %s\n' "$name" "$label" "$status" "$evidence"
      done
    printf '  Page-region hints do not prove playback territory. Native/ViaDNS is not established.\n'
}

printf 'VISHOW IP QUALITY REPORT: %s\nGenerated: %s\n' "$(read_field '.subject.ip // "Unknown IP"')" "$(read_field '.generated_at')"
show_basic
show_type
show_score
show_factor
show_media
printf '\nNo author counter or public report upload. Tested services see your source IP.\n'
exit "$result"
