#!/usr/bin/env bash
# reset_chrome_profiles — Pipeline de reset destructivo de perfiles de Chromium.
#
# Compone funciones del registry para: hacer backup de los bookmarks de todos los perfiles,
# cerrar chromium, borrar los perfiles (carpeta + entradas en Local State), recrearlos
# (la managed policy reinstala la whitelist de extensiones: uBlock + web_proxy), restaurar
# los bookmarks y verificar que cada perfil quedó solo con la whitelist.
#
# DESTRUCTIVO: borra cookies, logins, historial y contraseñas de los perfiles. Solo los
# bookmarks se preservan (backup + restore). Requiere --yes en modo real (o --dry-run).
#
# Uso:
#   reset_chrome_profiles --user-data-dir <dir>
#       [--profile "<dir>=<legible>"]... [--backup-dir <dir>] [--base-port 9250]
#       [--keep <ext_id>]... [--dry-run] [--yes]
#
# Defaults de --profile (los 4 perfiles reales): "Default=Work" "Personal=Personal"
#   "Profile 1=Aurgi" "Automation=Automation".
# Default de --keep (whitelist esperada tras el reset): uBlock Origin Lite + web_proxy toggle.

reset_chrome_profiles() {
    local _udd="" _backup_dir="${HOME}/.local/share/web_scraping/bookmarks-backups"
    local _base_port=9250 _dry_run=0 _yes=0
    local -a _profiles=()
    local -a _keep=()

    while [[ $# -gt 0 ]]; do
        case "$1" in
            --user-data-dir) _udd="$2"; shift 2 ;;
            --profile)       _profiles+=("$2"); shift 2 ;;
            --backup-dir)    _backup_dir="$2"; shift 2 ;;
            --base-port)     _base_port="$2"; shift 2 ;;
            --keep)          _keep+=("$2"); shift 2 ;;
            --dry-run)       _dry_run=1; shift ;;
            --yes)           _yes=1; shift ;;
            -h|--help)
                grep '^#' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; return 0 ;;
            *) echo "reset_chrome_profiles: argumento desconocido: $1" >&2; return 1 ;;
        esac
    done

    if [[ -z "$_udd" ]]; then
        echo "reset_chrome_profiles: --user-data-dir es obligatorio" >&2; return 1
    fi
    if [[ ${#_profiles[@]} -eq 0 ]]; then
        _profiles=("Default=Work" "Personal=Personal" "Profile 1=Aurgi" "Automation=Automation")
    fi
    if [[ ${#_keep[@]} -eq 0 ]]; then
        _keep=("ddkjiahejlhfcafbddmgiahcphecmpfh" "nanldmckabfghgdebblpfbdbhphhbnde")
    fi

    # Localizar las funciones del registry que componemos.
    local _dir _root _browser
    _dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    _root="$(cd "$_dir/../../.." && pwd)"
    _browser="$_root/bash/functions/browser"
    local _f
    for _f in backup_chrome_bookmarks restore_chrome_bookmarks delete_chrome_profile create_chrome_profile; do
        if [[ ! -f "$_browser/$_f.sh" ]]; then
            echo "reset_chrome_profiles: falta función $_f en $_browser" >&2; return 1
        fi
        # shellcheck disable=SC1090
        source "$_browser/$_f.sh"
    done

    echo "=== reset_chrome_profiles ==="
    echo "  user-data-dir : $_udd"
    echo "  perfiles      : ${_profiles[*]}"
    echo "  whitelist ext : ${_keep[*]}"
    echo "  backup-dir    : $_backup_dir"
    echo "  modo          : $([[ $_dry_run -eq 1 ]] && echo DRY-RUN || echo REAL)"
    echo ""

    # Confirmación obligatoria en modo real.
    if [[ $_dry_run -eq 0 && $_yes -eq 0 ]]; then
        echo "reset_chrome_profiles: operación DESTRUCTIVA (se pierden cookies/logins/historial)." >&2
        echo "  Repite con --yes para confirmar, o usa --dry-run para previsualizar." >&2
        return 3
    fi

    # ── [1/6] Backup de bookmarks (solo lee; chromium puede estar abierto) ──────
    echo "[1/6] Backup de bookmarks..."
    local _bk_json _ts_dir
    if [[ $_dry_run -eq 1 ]]; then
        backup_chrome_bookmarks --user-data-dir "$_udd" --backup-dir "$_backup_dir" --dry-run
        _ts_dir="<dry-run>"
    else
        _bk_json="$(backup_chrome_bookmarks --user-data-dir "$_udd" --backup-dir "$_backup_dir")" || {
            echo "reset_chrome_profiles: backup falló" >&2; return 1; }
        echo "$_bk_json"
        _ts_dir="$(printf '%s' "$_bk_json" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["backup_dir"]+"/"+d["ts"])')"
        echo "  backup en: $_ts_dir"
    fi
    echo ""

    # ── [2/6] Cerrar chromium que tenga ESTE user-data-dir abierto ─────────────
    echo "[2/6] Cerrando chromium con --user-data-dir=$_udd ..."
    if [[ $_dry_run -eq 1 ]]; then
        echo "  (dry-run: no se cierra nada)"
    else
        # Por-PID con comm=chromium (pgrep -x) para no auto-matchear grep/pgrep (el path del udd
        # contiene la cadena "chromium").
        local _p _kpids _i=0
        _kpids=""
        for _p in $(pgrep -x chromium 2>/dev/null); do
            tr '\0' ' ' < "/proc/$_p/cmdline" 2>/dev/null | grep -qF -- "$_udd" && _kpids="$_kpids $_p"
        done
        if [[ -n "${_kpids// }" ]]; then
            # shellcheck disable=SC2086
            kill -TERM $_kpids 2>/dev/null || true
            while :; do
                _kpids=""
                for _p in $(pgrep -x chromium 2>/dev/null); do
                    tr '\0' ' ' < "/proc/$_p/cmdline" 2>/dev/null | grep -qF -- "$_udd" && _kpids="$_kpids $_p"
                done
                [[ -z "${_kpids// }" ]] && break
                _i=$((_i+1)); [[ $_i -ge 20 ]] && { kill -9 $_kpids 2>/dev/null || true; break; }
                sleep 0.5
            done
            echo "  chromium cerrado."
        else
            echo "  (no había chromium con ese user-data-dir)"
        fi
    fi
    echo ""

    # ── [3/6] Borrar perfiles (carpeta + Local State) ──────────────────────────
    echo "[3/6] Borrando perfiles..."
    local _del_args=() _pair _pdir
    for _pair in "${_profiles[@]}"; do
        _pdir="${_pair%%=*}"
        _del_args+=(--profile "$_pdir")
    done
    if [[ $_dry_run -eq 1 ]]; then
        delete_chrome_profile --user-data-dir "$_udd" "${_del_args[@]}" --dry-run
    else
        delete_chrome_profile --user-data-dir "$_udd" "${_del_args[@]}" || {
            echo "reset_chrome_profiles: delete falló" >&2; return 1; }
    fi
    echo ""

    # ── [4/6] Recrear perfiles (la policy reinstala la whitelist al arrancar) ───
    echo "[4/6] Recreando perfiles..."
    local _idx=0 _name _port
    for _pair in "${_profiles[@]}"; do
        _pdir="${_pair%%=*}"; _name="${_pair#*=}"; _port=$((_base_port + _idx))
        if [[ $_dry_run -eq 1 ]]; then
            create_chrome_profile --user-data-dir "$_udd" --profile "$_pdir" --name "$_name" --port "$_port" --dry-run
        else
            create_chrome_profile --user-data-dir "$_udd" --profile "$_pdir" --name "$_name" --port "$_port" || {
                echo "reset_chrome_profiles: create de '$_pdir' falló" >&2; return 1; }
        fi
        _idx=$((_idx+1))
    done
    echo ""

    # ── [5/6] Restaurar bookmarks ──────────────────────────────────────────────
    echo "[5/6] Restaurando bookmarks..."
    if [[ $_dry_run -eq 1 ]]; then
        echo "  (dry-run: restauraría desde el backup recién creado)"
    else
        restore_chrome_bookmarks --user-data-dir "$_udd" --backup-dir "$_ts_dir" || {
            echo "reset_chrome_profiles: restore falló (continúo a verify)" >&2; }
    fi
    echo ""

    # ── [6/6] Verificar extensiones por perfil (carpetas en Extensions/) ───────
    echo "[6/6] Verificando extensiones (esperado: solo la whitelist)..."
    if [[ $_dry_run -eq 1 ]]; then
        echo "  (dry-run: verificaría que cada perfil tiene solo ${_keep[*]})"
        echo ""
        echo "reset_chrome_profiles: DRY-RUN completado, nada se modificó."
        return 0
    fi
    local _ok=1
    for _pair in "${_profiles[@]}"; do
        _pdir="${_pair%%=*}"
        local _extdir="$_udd/$_pdir/Extensions"
        local -a _present=()
        if [[ -d "$_extdir" ]]; then
            local _e
            for _e in "$_extdir"/*/; do
                _e="$(basename "$_e")"
                [[ "$_e" == "Temp" || "$_e" == "*" ]] && continue
                _present+=("$_e")
            done
        fi
        # Comprobar que todo lo presente está en la whitelist.
        local _extra=()
        local _id _found
        for _id in "${_present[@]}"; do
            _found=0
            local _k
            for _k in "${_keep[@]}"; do [[ "$_id" == "$_k" ]] && _found=1; done
            [[ $_found -eq 0 ]] && _extra+=("$_id")
        done
        if [[ ${#_extra[@]} -gt 0 ]]; then
            echo "  ✗ $_pdir: extensiones fuera de whitelist: ${_extra[*]}"
            _ok=0
        else
            echo "  ✓ $_pdir: ${_present[*]:-<vacío, aún sin arrancar>}"
        fi
    done
    echo ""
    if [[ $_ok -eq 1 ]]; then
        echo "reset_chrome_profiles: OK — perfiles recreados, bookmarks restaurados, solo la whitelist presente."
        return 0
    else
        echo "reset_chrome_profiles: verificación con avisos (revisar arriba)." >&2
        return 1
    fi
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    reset_chrome_profiles "$@"
fi
