#!/usr/bin/env ruby
# Standalone Anaquel API client. Requires only the Ruby standard library.
require "json"
require "base64"
require "digest"
require "tempfile"
require "csv"
require "stringio"
require "net/http"
require "openssl"
require "optparse"
require "uri"
require "timeout"
require "time"
require "socket"

module AnaquelCLI
  VERSION = "1.6.0"
  HELP = <<~TEXT
    Anaquel · Cliente de API
    Uso: anaquel COMANDO [opciones]

    whoami                             Consultar operador, rol y ubicación
    discover [RUTA] [--mine] [--schemas]  Ver operaciones de mi clave o el contrato completo
    find TEXTO [--param NOMBRE=VALOR]  Encontrar rutas y filtros autorizados por tema
    search TEXTO [--param NOMBRE=VALOR] Buscar por título, autor o código
    product ID                         Consultar un artículo
    get RUTA [--param NOMBRE=VALOR]     Leer una respuesta JSON
    batch [--file ARCHIVO|-]           Ejecutar en paralelo hasta 8 consultas GET
    list RUTA [--all] [--param N=V]     Leer páginas, una línea JSON por página
    invoice-download FOLIO xml|acuse --output ARCHIVO  Guardar un XML fiscal en un archivo nuevo
    invoice-download DEVOLUCION nota --output ARCHIVO   Guardar el XML de la nota de crédito
    reconcile-terminal TURNO --file ARCHIVO.csv  Comparar un lote local con el turno cerrado
    receipt-preview ARCHIVO                Abrir un borrador de recepción desde PDF o Excel
    purchase-draft --line ID=CANTIDAD --key CLAVE  Crear un borrador de compra
      --from-reorder                   Validar las cantidades sugeridas y guardar su cálculo
    write RUTA --key CLAVE [--file ARCHIVO|-]      Enviar un objeto JSON

    Configure ANAQUEL_API_URL (origen o /api/v1) y ANAQUEL_API_KEY en el entorno.
    Use HTTPS o una dirección local de loopback. Las rutas son relativas a /api/v1.
    Puede repetir --param y --line. write lee stdin de forma predeterminada.
    --retries N admite 0 a 3 reintentos transitorios (1 por defecto).
    Para reintentar una escritura conserve la misma clave, operador, ruta y cuerpo.
    Cada línea de list contiene offset, siguiente y resultado, la página original.
    batch acepta un arreglo JSON de objetos con ruta y parametros, y devuelve una línea por consulta.
    Use --version para consultar la versión instalada.
  TEXT

  class Failure < StandardError
    attr_reader :code, :status, :details
    def initialize(message, code=2, status=nil, details={})
      @code, @status, @details = code, status, details
      super(message)
    end
  end

  def self.path(value, template: false)
    path = value.to_s.sub(%r{\A/api/v1/}, "").sub(%r{\A/(?!/)}, "")
    allowed = template ? /\A(?:[a-zA-Z0-9._~-]+|\{[a-zA-Z0-9_]+\})\z/ : /\A[a-zA-Z0-9._~-]+\z/
    parts = path.split("/", -1)
    unless !parts.empty? && parts.all? { |part| part.match?(allowed) && !%w[. ..].include?(part) }
      raise Failure, "Indique una ruta de la API sin URL, consulta ni segmentos relativos. Use --param para los filtros."
    end
    "/" + path
  end

  class Client
    MAX_RESPONSE = 16 * 1024 * 1024
    TRANSIENT = [408, 425, 429, 500, 502, 503, 504].freeze
    CONNECTION_ERRORS = [Timeout::Error, EOFError, SocketError, Errno::ECONNRESET, Errno::ECONNREFUSED,
      Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ETIMEDOUT, Errno::EPIPE].freeze

    def initialize(env, retries)
      @key = env["ANAQUEL_API_KEY"].to_s
      raise Failure, "Configure ANAQUEL_API_KEY con una credencial válida." unless @key.match?(/\A[!-~]+\z/)
      @base = URI.parse(env.fetch("ANAQUEL_API_URL", ""))
      loopback = @base.hostname == "localhost" || @base.hostname == "::1" ||
        (@base.hostname.to_s.match?(/\A127(?:\.(?:0|[1-9][0-9]{0,2})){3}\z/) && @base.hostname.split(".").all? { |n| n.to_i <= 255 })
      unless @base.is_a?(URI::HTTP) && !@base.host.to_s.empty? && @base.port.between?(1,65_535) && !@base.userinfo &&
             !@base.query && !@base.fragment && ["","/","/api/v1","/api/v1/"].include?(@base.path) &&
             (@base.scheme == "https" || (@base.scheme == "http" && loopback))
        raise Failure, "ANAQUEL_API_URL debe ser un origen HTTPS o HTTP de loopback, opcionalmente con /api/v1."
      end
      @retries = retries
    rescue URI::Error
      raise Failure, "ANAQUEL_API_URL inválida."
    end

    def call(method, path, params={}, body:nil, key:nil, xml:false)
      uri = @base.dup
      relative = AnaquelCLI.path(path)
      uri.path = method == "GET" && relative == "/health" ? "/health" : "/api/v1" + relative
      uri.query = URI.encode_www_form(params) unless params.empty?
      count = 0
      loop do
        begin
          status, bytes, delay, headers = exchange(uri, method, body, key, xml ? "application/xml" : "application/json")
        rescue *CONNECTION_ERRORS
          if count < @retries
            pause(count); count += 1; next
          end
          raise Failure.new("Conexión interrumpida. Para una escritura vuelva a usar la misma clave y el mismo cuerpo.", 5)
        rescue OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError, IOError
          raise Failure.new("No se pudo verificar la conexión TLS o la respuesta HTTP.", 5)
        end
        if TRANSIENT.include?(status) && count < @retries
          retry_after = retry_seconds(delay)
          if retry_after.nil? || retry_after <= 5
            pause(count, retry_after); count += 1; next
          end
        end
        if status.between?(300,399)
          raise Failure.new("La API respondió con una redirección. Verifique ANAQUEL_API_URL.", 5, status)
        end
        if xml && status.between?(200,299)
          unless status==200 && headers.fetch("content-type","").split(";").first.to_s.strip.downcase=="application/xml" && !bytes.empty?
            raise Failure.new("La API no devolvió el XML fiscal solicitado.",5,status)
          end
          digest=headers["content-digest"]
          if digest && digest!="sha-256=:"+Base64.strict_encode64(Digest::SHA256.digest(bytes))+":"
            raise Failure.new("La huella del XML recibido difiere de la comunicada por la API.",5,status)
          end
          return bytes
        end
        data = begin
          JSON.parse(bytes)
        rescue JSON::ParserError, EncodingError
          nil
        end
        unless status.between?(200,299)
          msg = data.is_a?(Hash) && data["error"].is_a?(String) ? data["error"] : "La API rechazó la solicitud."
          code = [401,403].include?(status) ? 3 : (status == 409 ? 6 : (status >= 500 ? 5 : 4))
          details={}
          if status==409 && method=="POST" && data.is_a?(Hash)
            details=data.slice("reposicion_actualizada") if relative=="/compras/borradores"
            if relative=="/inventario/documentos" && data["conteo_modificado"]==true && data["cambios"].is_a?(Array)
              changes=data["cambios"].select{|change|change.is_a?(Hash)}.map{|change|change.slice("book","expected","current","revision_movimientos")}
              details={"conteo_modificado"=>true,"cambios"=>changes}
            end
            details=data.slice("revision_borrador") if relative=="/compras/pedidos"
            details=data.slice("costo_modificado") if relative=="/catalogo/costo"
            if %w[/inventario/importaciones/confirmar /compras/recepciones].include?(relative) && data["codigo"]=="REFERENCIA_RECEPCION_DUPLICADA"
              details=data.slice("codigo","recepcion_existente")
            end
          end
          raise Failure.new(msg[0,512], code, status, details)
        end
        raise Failure.new("La ruta solicitada no devolvió JSON. get y list admiten respuestas JSON.",5,status) if data.nil? && bytes.strip != "null"
        return data
      end
    end

    def retry_seconds(header)
      return nil if header.to_s.empty?
      value = header.to_s
      return value.to_i if value.match?(/\A[0-9]+\z/)
      [Time.httpdate(value) - Time.now, 0].max
    rescue ArgumentError
      nil
    end

    def pause(count, delay=nil)
      sleep(delay || 0.25 * 2**count)
    end

    def exchange(uri, method, body, key, accept)
      http = Net::HTTP.new(uri.hostname, uri.port, nil)
      http.use_ssl = uri.scheme == "https"
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER if http.use_ssl?
      http.open_timeout = 5
      http.read_timeout = 30
      http.write_timeout = 30 if http.respond_to?(:write_timeout=)
      http.max_retries = 0 if http.respond_to?(:max_retries=)
      req = (method == "GET" ? Net::HTTP::Get : Net::HTTP::Post).new(uri.request_uri)
      req["Authorization"] = "Bearer " + @key unless uri.path == "/health"
      req["Accept"] = accept
      req["Accept-Encoding"] = "identity" if accept=="application/xml"
      req["User-Agent"] = "Anaquel-CLI/" + VERSION
      if body
        req["Content-Type"] = "application/json"
        req["Idempotency-Key"] = key
        req.body = body
      end
      http.start do |connection|
        connection.request(req) do |res|
          bytes = String.new(encoding:Encoding::BINARY)
          res.read_body do |piece|
            raise Failure.new("Respuesta demasiado grande. Use filtros y paginación.",5) if bytes.bytesize + piece.bytesize > MAX_RESPONSE
            bytes << piece
          end
          if accept=="application/xml" && res["content-length"] && res["content-length"]!=bytes.bytesize.to_s
            raise EOFError
          end
          return res.code.to_i, bytes, res["retry-after"], res.each_header.to_h
        end
      end
    end
  end

  # Voucher data stays on the workstation. The server receives only the shift
  # ID and the pagination parameters for its existing role-scoped journal.
  class TerminalReconciliation
    COLUMNS=%w[folio tipo importe].freeze
    STATES=%w[duplicado sin_folio importe solo_terminal solo_anaquel coincide].freeze
    MAX_FILE=2*1024*1024
    MAX_SAFE=9_007_199_254_740_991

    def initialize(client,id)
      @client,@id=client,id
      raise Failure,"Indique el folio del turno." unless id.size.between?(1,240) && !id.match?(/[[:cntrl:]]/)
      @groups={}
      @unreferenced=[]
      @totals={"terminal"=>{}, "anaquel"=>{}}
      @totals.each_value{|v|v.merge!("cobros"=>0,"devoluciones"=>0,"neto"=>0)}
    end

    def reference?(value)
      value.is_a?(String) && value.encode("UTF-16LE").bytesize<=128 && value==value.strip &&
        value.match?(/\A[\p{L}0-9 .\/#:_-]+\z/u) && value.match?(/[\p{L}0-9]/u) &&
        !value.delete(" ./#:_-").match?(/[0-9]{13}/)
    end

    def trim_cell(value)
      value.gsub(/\A[\p{Zs}\t\v\f\uFEFF\u2028\u2029]+|[\p{Zs}\t\v\f\uFEFF\u2028\u2029]+\z/u,"")
    end

    def vouchers(path)
      raise Failure,"Seleccione el CSV con --file ARCHIVO." unless path && File.file?(path)
      bytes=File.open(path,"rb"){|f|f.read(MAX_FILE+1)}.to_s.force_encoding("UTF-8")
      raise Failure,"El archivo supera 2 MiB." if bytes.bytesize>MAX_FILE
      raise Failure,"Se requiere un CSV en UTF-8." unless bytes.valid_encoding?
      lines=StringIO.new(bytes.sub(/\A\uFEFF/,"").gsub(/\r\n?/,"\n"))
      header=lines.gets.to_s.chomp
      delimiter=[",",";","\t"].find{|sep|header.include?(sep)}
      names=CSV.parse_line(header,col_sep:delimiter).map{|v|trim_cell(v.to_s).downcase} if delimiter
      raise Failure,"Use las tres columnas folio, tipo e importe." unless names && names.sort==COLUMNS.sort
      count=0
      lines.each_line.with_index(2) do |raw_line,number|
        line=raw_line.chomp
        next if trim_cell(line).empty?
        raise Failure,"El máximo por lote es de 10 000 operaciones." if (count+=1)>10_000
        cells=CSV.parse_line(line,col_sep:delimiter)
        raise Failure,"Se requieren tres columnas en la línea #{number}." unless cells && cells.size==3
        folio,kind,raw=COLUMNS.map{|name|cells[names.index(name)].to_s}
        kind=trim_cell(kind).downcase
        amount=/\A([0-9]{1,7})(?:\.([0-9]{1,2}))?\z/.match(trim_cell(raw))
        cents=amount && amount[1].to_i*100+amount[2].to_s.ljust(2,"0").to_i
        unless reference?(folio) && %w[cobro devolucion].include?(kind) && cents && cents.positive?
          raise Failure,"Revise el folio de operación, el tipo y el importe positivo en la línea #{number}."
        end
        record("terminal",folio,kind,kind=="cobro" ? cents : -cents,number)
      end
    rescue CSV::MalformedCSVError
      raise Failure,"Revise las comillas del CSV. Cada operación ocupa una sola línea."
    rescue SystemCallError, IOError
      raise Failure,"No se pudo leer el archivo de la terminal."
    end

    def record(side,folio,kind,amount,source)
      total=@totals.fetch(side)
      field=kind=="cobro" ? "cobros" : "devoluciones"
      total[field]=integer(total[field]+amount.abs)
      total["neto"]=integer(total["neto"]+amount)
      row=@groups[[folio,kind]] if folio
      unless row
        row={"folio"=>folio,"tipo"=>kind,"terminal"=>nil,"anaquel"=>nil,"documentos"=>[],
          "operaciones_terminal"=>0,"operaciones_anaquel"=>0,"partidas_terminal"=>[],"partidas_anaquel"=>[]}
        folio ? @groups[[folio,kind]]=row : @unreferenced<<row
      end
      row[side]=integer(row[side].to_i+amount)
      row["operaciones_"+side]+=1
      row["partidas_"+side]<<{(side=="terminal" ? "linea" : "folio")=>source,"centavos"=>amount}
      row["documentos"]<<source if side=="anaquel"
    end

    def verify(condition)
      raise Failure.new("No se pudo verificar el diario completo contra el resumen del turno.",5) unless condition
    end

    def integer(value)
      verify(value.is_a?(Integer) && value.abs<=MAX_SAFE)
      value
    end

    def basis(page)
      verify(page.is_a?(Hash) && page["turno"].is_a?(Hash) && page["turno"]["id"]==@id)
      shift=page["turno"]
      raise Failure.new("Cierre el turno antes de cotejar la terminal.",6) unless shift["closed"]
      sales,refunds=page.values_at("pagos","devoluciones")
      verify([sales,refunds].all?{|group|group.is_a?(Hash)})
      sc,st,rc,rt=[sales,refunds].flat_map{|group|%w[efectivo tarjeta].map{|k|integer(group.fetch(k,0))}}
      verify([sc,st,rc,rt].all?{|value|value>=0})
      cash=integer(sc-rc+integer(page["movimientos_efectivo"]))
      opening=integer(shift["opening"])
      counted=integer(shift["counted"])
      expected=integer(page["esperado"])
      verify(opening>=0 && counted>=0 && expected==integer(opening+cash) && page["diferencia"]==integer(counted-expected))
      batch=page["terminal"]
      if !batch.nil?
        verify(batch.is_a?(Hash) && integer(batch["esperado"])==st-rt)
        verify(integer(batch["diferencia"])==integer(integer(batch["reportado"])-batch["esperado"]))
        verify(batch["referencia"].nil? || batch["referencia"].is_a?(String))
      end
      {closed:shift["closed"],location:shift["location"],cash:cash,opening:opening,counted:counted,expected:expected,
       difference:page["diferencia"],sales:st,refunds:rt,batch:batch,apuntes:integer(page.dig("seleccion","apuntes"))}
    end

    def journal
      offset=0
      seen={}; card_documents={}
      cash=0
      expected=nil
      loop do
        page=@client.call("GET","/informes/fuentes/turno",{"id"=>@id,"pago"=>"todos","ordenar"=>"at","direccion"=>"asc","offset"=>offset.to_s})
        verify(page.is_a?(Hash) && page["seleccion"].is_a?(Hash))
        current=basis(page)
        expected ||= current
        count=expected[:apuntes]
        rows=page["movimientos"]
        verify(expected==current && count>=offset && rows.is_a?(Array) && rows.size==[50,count-offset].min &&
          page.dig("seleccion","tarjeta")==expected[:sales]-expected[:refunds] && page.dig("seleccion","efectivo")==expected[:cash])
        rows.each do |row|
          verify(row.is_a?(Hash))
          kind,id=row.values_at("tipo","folio")
          verify(id.is_a?(String) && !id.empty? && %w[venta devolucion movimiento_efectivo].include?(kind) && !seen[[kind,id]])
          seen[[kind,id]]=true
          cash=integer(cash+integer(row["efectivo"]))
          amount=integer(row["tarjeta"])
          next if amount.zero?
          verify(!card_documents[id] && (kind=="venta" && amount.positive? || kind=="devolucion" && amount.negative?))
          card_documents[id]=true
          ref=row["referencia_terminal"]
          ref=nil if ref==""
          verify(ref.nil? || reference?(ref))
          record("anaquel",ref,kind=="venta" ? "cobro" : "devolucion",amount,id)
        end
        offset+=rows.size
        verify(page.key?("siguiente") && page["siguiente"]==(offset<count ? offset : nil))
        break if offset==count
      end
      verify(cash==expected[:cash] && @totals["anaquel"].values_at("cobros","devoluciones")==expected.values_at(:sales,:refunds))
      expected
    end

    def state(row)
      return "sin_folio" unless row["folio"]
      return "duplicado" if row["operaciones_terminal"]>1 || row["operaciones_anaquel"]>1
      return "solo_terminal" if row["anaquel"].nil?
      return "solo_anaquel" if row["terminal"].nil?
      row["terminal"]==row["anaquel"] ? "coincide" : "importe"
    end

    def run(path)
      vouchers(path)
      shift=journal
      rows=@groups.values+@unreferenced
      counts=STATES.to_h{|s|[s,0]}
      rows.each{|r|counts[r["estado"]=state(r)]+=1}
      rows.sort_by!{|r|[STATES.index(r["estado"]),r["folio"].to_s.downcase,r["folio"].to_s,r["tipo"]]}
      csv=@totals["terminal"]["neto"];system_net=@totals["anaquel"]["neto"]
      difference=integer(csv-system_net);batch=shift[:batch]
      reported=batch && batch["reportado"]
      issues=rows.size-counts["coincide"]
      variances=[difference,shift[:difference],batch && batch["diferencia"]].compact
      status=if issues>0 || variances.any?{|v|v!=0} then "con_diferencias"
             elsif reported.nil? then "sin_corte"
             else "cuadrado"
             end
      control={"estado"=>status,"caja"=>{"esperado"=>shift[:expected],"contado"=>shift[:counted],"diferencia"=>shift[:difference]},
        "tarjeta"=>{"csv"=>csv,"anaquel"=>system_net,"reportado"=>reported,"referencia_lote"=>batch && batch["referencia"],
          "csv_menos_anaquel"=>difference,"csv_menos_reportado"=>reported && integer(csv-reported),"reportado_menos_anaquel"=>batch && batch["diferencia"]},
        "casos"=>counts}
      @totals.merge("turno"=>@id,"apuntes"=>shift[:apuntes],"diferencia"=>difference,"coincidencias"=>counts["coincide"],
        "incidencias"=>issues,"filas"=>rows,"control"=>control)
    end
  end

  class Command
    MAX_INPUT = 8 * 1024 * 1024
    def initialize(env: ENV, input: $stdin, output: $stdout, error: $stderr, client: Client)
      @env, @input, @output, @error, @client_type = env,input,output,error,client
    end

    def run(argv)
      args = argv.dup
      cmd = args.shift
      if cmd.nil? || ["help","--help","-h"].include?(cmd) || args.include?("--help")
        @output.puts HELP
        return 0
      elsif cmd == "--version"
        @output.puts VERSION
        return 0
      end
      @params, @lines, @retries, @from_reorder = {}, [], 1, false
      @all, @file, @key, @mine, @schemas, @schema = false, nil, nil, false, false, nil
      @destination=nil
      parse_options(cmd, args)
      @client = @client_type.new(@env,@retries)
      result = case cmd
      when "whoami"
        arity(args,0); read("/sesion")
      when "discover"
        raise Failure, "Indique una sola ruta." if args.size > 1
        discover(args.first)
      when "find"
        arity(args,1)
        raise Failure,"Indique los términos de búsqueda una sola vez." if args.first.strip.empty? || @params.key?("q")
        read("/operaciones",@params.merge("q"=>args.first))
      when "product"
        arity(args,1); read("/catalogo/producto",{"id"=>args.first})
      when "search"
        arity(args,1)
        raise Failure, "Indique un texto de búsqueda." if args.first.strip.empty?
        raise Failure, "El término de búsqueda ya se indicó." if @params.key?("q")
        read("/catalogo",@params.merge("q"=>args.first))
      when "get"
        arity(args,1); read(AnaquelCLI.path(args.first),@params)
      when "list"
        arity(args,1); pages(AnaquelCLI.path(args.first)); return 0
      when "batch"
        arity(args,0); return batch
      when "write"
        arity(args,1); write(AnaquelCLI.path(args.first), read_body)
      when "invoice-download"
        arity(args,2); download_invoice(args[0],args[1])
      when "reconcile-terminal"
        arity(args,1); TerminalReconciliation.new(@client,args.first).run(@file)
      when "receipt-preview"
        arity(args,1); preview_receipt(args.first)
      when "purchase-draft"
        arity(args,0)
        raise Failure, "Indique de 1 a 200 partidas con --line ID=CANTIDAD." unless @lines.size.between?(1,200)
        raise Failure, "Repita cada artículo una sola vez." if @lines.map { |l| l["book"] }.uniq.size != @lines.size
        body={"lines"=>@lines}
        if @from_reorder
          body["origen"]="reposicion"
          @lines.each{|line|line["sugerida"]=line.fetch("quantity")}
        end
        write("/compras/borradores",JSON.generate(body))
      end
      emit(@output,result)
      0
    rescue Failure => e
      problem = {"error"=>e.message}
      problem["http"] = e.status if e.status
      emit(@error,problem.merge(e.details))
      e.code
    rescue OptionParser::ParseError
      emit(@error,{"error"=>"Opción o valor inválido. Consulte anaquel --help."})
      2
    rescue Errno::EPIPE
      0
    end

    def parse_options(cmd, args)
      known = %w[whoami discover find product search get list batch write receipt-preview purchase-draft reconcile-terminal invoice-download]
      raise Failure, "Comando desconocido. Consulte anaquel --help." unless known.include?(cmd)
      parser = OptionParser.new
      parser.on("--retries N") do |value|
        raise Failure,"--retries admite valores de 0 a 3." unless value.match?(/\A[0-3]\z/)
        @retries = value.to_i
      end
      if %w[find search get list].include?(cmd)
        parser.on("--param NOMBRE=VALOR") do |pair|
          name, value = pair.split("=",2)
          unless name.to_s.match?(/\A[A-Za-z][A-Za-z0-9_]*\z/) && !value.nil? && !@params.key?(name)
            raise Failure,"Cada filtro debe tener un nombre distinto y la forma --param NOMBRE=VALOR."
          end
          @params[name] = value
        end
      end
      if cmd == "discover"
        parser.on("--mine") { @mine = true }
        parser.on("--schemas") { @schemas = true }
      end
      parser.on("--output ARCHIVO") { |file| @destination=file } if cmd=="invoice-download"
      parser.on("--all") { @all = true } if cmd == "list"
      if %w[write purchase-draft].include?(cmd)
        parser.on("--key CLAVE") { |k| @key = k }
      end
      parser.on("--file ARCHIVO") { |file| @file = file } if %w[batch write reconcile-terminal].include?(cmd)
      if cmd == "purchase-draft"
        parser.on("--from-reorder") { @from_reorder=true }
        parser.on("--line ID=CANTIDAD") do |pair|
          book, separator, qty = pair.rpartition("=")
          unless separator == "=" && !book.strip.empty? && qty.match?(/\A[1-9][0-9]{0,3}\z/)
            raise Failure,"Use --line ID=CANTIDAD con una cantidad entre 1 y 9999."
          end
          @lines << {"book"=>book,"quantity"=>qty.to_i}
        end
      end
      parser.permute!(args)
      if %w[write purchase-draft].include?(cmd) && !@key.to_s.match?(/\A[A-Za-z0-9_-]{12,100}\z/)
        raise Failure, "Use --key con 12 a 100 letras, números, guiones o guiones bajos."
      end
    end

    def arity(args,n)
      raise Failure, "Argumentos incorrectos. Consulte anaquel --help." unless args.size == n
    end

    # Replace any echoed credential inside strings before JSON encoding.
    def redacted(data)
      key = @env["ANAQUEL_API_KEY"].to_s
      case data
      when String
        value = key.empty? ? data : data.gsub(key) { "[oculto]" }
        value.gsub(/cla_ag_[A-Za-z0-9_-]{43}/, "[oculto]")
      when Array then data.map { |item| redacted(item) }
      when Hash then data.each_with_object({}) { |(k,v),h| h[redacted(k)] = redacted(v) }
      else data
      end
    end

    def emit(io,value)
      io.puts JSON.generate(redacted(value),ascii_only:true)
    end

    def read(path,params={})
      @client.call("GET",path,params)
    end

    def batch_input
      source = @file && @file != "-" ? File.open(@file,"rb") : @input
      raise Failure,"Proporcione un arreglo JSON por stdin o con --file." if source.tty?
      raw = source.read(65_537)
      raise Failure,"El lote debe ocupar hasta 64 KiB." if raw.to_s.bytesize>65_536
      requests = JSON.parse(raw.to_s)
      raise Failure,"Envíe entre 1 y 8 consultas." unless requests.is_a?(Array) && requests.size.between?(1,8)
      requests.map do |request|
        unless request.is_a?(Hash) && (request.keys-%w[ruta parametros]).empty? && request["ruta"].is_a?(String)
          raise Failure,"Cada consulta requiere ruta y admite parametros."
        end
        params=request.fetch("parametros",{})
        unless params.is_a?(Hash) && params.size<=30 && params.all? { |name,value|
            /\A[A-Za-z][A-Za-z0-9_]*\z/.match?(name) &&
              (value.is_a?(String) || value.is_a?(Integer) || value==true || value==false) }
          raise Failure,"Use nombres de filtro y valores simples en parametros."
        end
        [AnaquelCLI.path(request.fetch("ruta")),params]
      end
    rescue JSON::ParserError, EncodingError, SystemCallError
      raise Failure,"No se pudo leer el arreglo JSON de consultas."
    ensure
      source&.close if source && source!=@input
    end

    def batch
      requests=batch_input
      pending=Queue.new
      requests.each_index { |i| pending << i }
      results=Array.new(requests.length)
      count=[4,requests.length].min
      count.times { pending << nil }
      workers=Array.new(count) do
        Thread.new do
          while (index = pending.pop)
            route,params=requests.fetch(index)
            record={"indice"=>index,"ruta"=>route}
            begin
              results[index]=[0,record.merge("resultado"=>read(route,params))]
            rescue Failure => error
              results[index]=[error.code,record.merge("error"=>error.message,"http"=>error.status)]
            end
          end
        end
      end
      workers.each(&:value)
      results.each { |_,record| emit(@output,record) }
      results.find { |code,_| code!=0 }&.first || 0
    end

    def schema
      @schema ||= begin
        doc = read("/openapi.json")
        unless doc.is_a?(Hash) && doc["paths"].is_a?(Hash)
          raise Failure.new("El servidor no devolvió un contrato OpenAPI válido.",5)
        end
        doc
      end
    end

    def route_entry(path)
      paths = schema.fetch("paths")
      return [path,paths.fetch(path)] if paths.key?(path)
      result = paths.find do |pattern,_|
        parts, actual = pattern.split("/"), path.split("/")
        parts.size == actual.size && parts.zip(actual).all? { |s,a| s == a || s.match?(/\A\{\w+\}\z/) }
      end
      raise Failure, "La ruta no está publicada en el contrato OpenAPI." unless result
      result
    end

    def contract(path)
      route_entry(path).last
    end

    def allowed?(verb,definition,session)
      return true unless session
      return false if session["agente"] && definition["x-requiere-titular"]
      return false if session["agente"] && verb != "get" && session["alcance"] != "lectura_escritura"
      Array(definition["x-roles"]).include?(session["role"]) || definition["security"] == []
    end

    def discover(route)
      raise Failure, "Indique una ruta para --schemas." if @schemas && !route
      session = read("/sesion") if @mine
      if @mine && !(session.is_a?(Hash) && session["role"].is_a?(String))
        raise Failure.new("La API no devolvió una sesión con rol.",5)
      end
      context = if session
        {"sesion"=>{"operator"=>session["operator"],"role"=>session["role"],"location"=>session["location"],
           "agente"=>session["agente"]==true,"alcance"=>session["alcance"]},
         "aviso"=>"El servidor comprueba la ubicación del puesto, los permisos específicos y el estado de cada documento."}
      else
        {}
      end
      if route
        path,methods = route_entry(AnaquelCLI.path(route,template:true))
        subset = methods.reject { |verb,definition| %w[get post].include?(verb) && !allowed?(verb,definition,session) }
        if @schemas
          result = schema.slice("openapi","info","servers","security").merge("paths"=>{path=>subset},"components"=>referenced_components(subset))
          context.each { |name,value| result["x-"+name]=value }
          return result
        end
        return @mine ? context.merge("ruta"=>path,"operaciones"=>subset.select { |verb,_| %w[get post].include?(verb) }) : subset
      end
      ops = schema.fetch("paths").sort.flat_map do |path,methods|
        %w[get post].map do |verb|
          definition = methods[verb]
          next unless definition && allowed?(verb,definition,session)
          {"metodo"=>verb.upcase,"ruta"=>path,"roles"=>definition["x-roles"],"resumen"=>definition["summary"]}
        end.compact
      end
      context.merge("version"=>schema.dig("info","version"),"operaciones"=>ops)
    end

    # Pull only local components, including nested response and parameter refs.
    def referenced_components(operations)
      result = {}
      schemes = schema.dig("components","securitySchemes")
      result["securitySchemes"] = schemes if schemes
      pending = [operations]
      until pending.empty?
        node = pending.pop
        if node.is_a?(Array)
          pending.concat(node)
        elsif node.is_a?(Hash)
          if (reference = node["$ref"])
            match = %r{\A#/components/([^/]+)/([^/]+)\z}.match(reference)
            raise Failure.new("El contrato contiene una referencia no local o desconocida.",5) unless match
            group,name = match.captures.map { |s| s.gsub("~1","/").gsub("~0","~") }
            result[group] ||= {}
            unless result[group].key?(name)
              value = schema.dig("components",group,name)
              raise Failure.new("El contrato contiene una referencia sin definición.",5) unless value
              result[group][name]=value
              pending << value
            end
          end
          pending.concat(node.values)
        end
      end
      result
    end

    def parameters(route,method)
      (Array(route["parameters"]) + Array(method["parameters"])).map do |parameter|
        ref = parameter["$ref"]
        if ref && ref.start_with?("#/components/parameters/")
          schema.dig("components","parameters",ref.split("/").last) || {}
        else
          parameter
        end
      end
    end

    def pages(path)
      route = contract(path)
      method = route["get"]
      unless method && parameters(route,method).any? { |p| p["in"] == "query" && p["name"] == "offset" }
        raise Failure,"La ruta no declara paginación por offset. Utilice get."
      end
      first = @params.fetch("offset","0")
      raise Failure, "offset debe ser un entero positivo o cero." unless first.match?(/\A[0-9]+\z/)
      offset = first.to_i
      loop do
        page = read(path,@params.merge("offset"=>offset.to_s))
        following = if page.is_a?(Array)
          offset + page.length if page.length >= 50
        elsif page.is_a?(Hash) && page.key?("siguiente")
          case page["siguiente"]
          when false, nil then nil
          when true
            # Some responses also have diario, estados or movimientos_efectivo;
            # only the collection indicated by the route advances its offset.
            field = case path
            when "/inventario/escanear" then "candidatos"
            when "/inventario/historial-articulo" then "registros"
            when "/ventas/comparativo" then "grupos"
            when %r{\A/informes/fuentes/(?:turno|inventario)\z} then "movimientos"
            when %r{\A/proveedores/pedidos/historico/} then "partidas"
            else "filas"
            end
            records = page[field]
            raise Failure.new("La API indicó otra página sin filas para avanzar.",5) unless records.is_a?(Array) && !records.empty?
            offset + records.length
          else page["siguiente"]
          end
        else
          raise Failure.new("Respuesta sin arreglo ni cursor siguiente. Utilice get para esta ruta.",5)
        end
        unless following.nil? || (following.is_a?(Integer) && following > offset)
          raise Failure.new("La API devolvió un cursor inválido.",5)
        end
        emit(@output,{"offset"=>offset,"siguiente"=>following,"resultado"=>page})
        break unless @all && following
        offset = following
      end
    end

    def read_body
      file = @file && @file != "-" ? File.open(@file,"rb") : @input
      raise Failure, "Proporcione el objeto JSON por stdin o con --file." if file.tty?
      bytes = file.read(MAX_INPUT+1).to_s
      raise Failure, "El objeto JSON supera 8 MiB." if bytes.bytesize > MAX_INPUT
      bytes = bytes.dup.force_encoding(Encoding::UTF_8)
      unless bytes.valid_encoding? && JSON.parse(bytes).is_a?(Hash)
        raise Failure, "El cuerpo debe ser un objeto JSON en UTF-8."
      end
      bytes
    rescue JSON::ParserError
      raise Failure, "El cuerpo debe ser un objeto JSON válido."
    rescue SystemCallError, IOError
      raise Failure, "No se pudo leer el archivo JSON."
    ensure
      file.close if file && file != @input
    end

    def download_invoice(folio,artifact)
      unless /\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/i.match?(folio) && %w[xml acuse nota].include?(artifact)
        raise Failure,"Indique un folio válido y el tipo de XML (xml, acuse o nota)."
      end
      if @destination.to_s.empty? || @destination=="-"
        raise Failure,"Use --output con la ruta de un archivo nuevo."
      end
      raise Errno::EEXIST if File.exist?(@destination) || File.symlink?(@destination)
      route=artifact=="nota" ? "/facturacion/notas-credito/"+folio.downcase+"/xml" : "/facturacion/solicitudes/"+folio.downcase+"/"+artifact
      bytes=@client.call("GET",route,xml:true)
      # Publish the complete private file exclusively, including when two callers choose the same path.
      Tempfile.create(".anaquel-xml-",File.dirname(@destination)) do |file|
        file.binmode
        file.write(bytes)
        file.fsync
        file.close
        File.link(file.path,@destination)
      end
      {"sha256"=>Digest::SHA256.hexdigest(bytes),"bytes"=>bytes.bytesize}
    rescue Errno::EEXIST
      raise Failure,"El destino ya existe. Elija un archivo nuevo."
    rescue SystemCallError,IOError
      raise Failure,"No se pudo guardar el XML en el archivo indicado."
    end

    def preview_receipt(path)
      name=File.basename(path)
      unless %w[.pdf .xls .xlsx].include?(File.extname(name).downcase) && File.file?(path)
        raise Failure,"Seleccione un archivo PDF o Excel de la entrega."
      end
      max_bytes=5*1024*1024
      bytes=File.open(path,"rb"){|file|file.read(max_bytes+1)}
      unless bytes && bytes.bytesize.between?(1,max_bytes)
        raise Failure,"El archivo debe contener datos y medir hasta 5 MB."
      end
      # The server identifies the draft by store, movement kind and exact bytes.
      body=JSON.generate("tipo"=>"recepcion","nombre"=>name,"contenido"=>Base64.strict_encode64(bytes))
      @client.call("POST","/inventario/importaciones/previsualizar",{},body:body)
    rescue SystemCallError,IOError
      raise Failure,"No se pudo leer el archivo de la entrega."
    end

    def write(path,body)
      route = contract(path)
      operation = route["post"]
      raise Failure, "La ruta no admite POST." unless operation
      idempotent = parameters(route,operation).any? { |p| p["in"] == "header" && p["name"].to_s.downcase == "idempotency-key" }
      if @retries > 0 && !idempotent
        raise Failure, "Esta operación no declara Idempotency-Key. Use --retries 0 para enviarla una sola vez."
      end
      @client.call("POST",path,{},body:body,key:@key)
    end
  end
end

exit AnaquelCLI::Command.new.run(ARGV) if $PROGRAM_NAME == __FILE__
