"""Example backend integration. Set non-secret environment values and run locally."""
import getpass
import json
import os
from pathlib import Path

import httpx


def consultar_rcv(*, url, token, rut, clave, empresa, periodo, operacion='compra'):
    if operacion not in ('compra', 'venta'):
        raise ValueError('operacion debe ser compra o venta')
    route = 'compras' if operacion == 'compra' else 'ventas'
    with httpx.Client(timeout=httpx.Timeout(900, connect=10)) as client:
        response = client.post(url.rstrip('/') + '/api/v1/rcv/' + route,
            headers={'Authorization': 'Bearer ' + token},
            json={'rut': rut, 'clave': clave, 'rut_empresa': empresa, 'periodo': periodo,
                  'consulta': 'detalle_todos', 'estado': 'REGISTRO'})
        if response.is_error:
            raise RuntimeError(f'Consulta rechazada: HTTP {response.status_code}. '
                               'Revisa permisos, cuota y parámetros en la documentación.')
        return response.json()


def main():
    result = consultar_rcv(
        url=os.environ.get('RCV_API_URL', 'http://127.0.0.1:8010'),
        token=os.environ.get('RCV_API_TOKEN') or getpass.getpass('Token API: '),
        rut=os.environ.get('SII_RUT') or input('RUT de inicio de sesión: '),
        clave=os.environ.get('SII_CLAVE') or getpass.getpass('Clave tributaria de ese RUT: '),
        empresa=os.environ.get('SII_RUT_EMPRESA') or input('RUT de la empresa: '),
        periodo=os.environ.get('RCV_PERIODO') or input('Período YYYY-MM: '),
        operacion=os.environ.get('RCV_OPERACION', 'compra'))
    print(f"Documentos recibidos: {result['total_documentos']}")
    print('Descarga completa' if result['completo'] else 'Descarga parcial: revisa tipos')
    # Save the complete result before acting on a partial download.
    path = Path('resultado_rcv.json')
    path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
    print(f'Archivo: {path.resolve()}')
    return 0 if result['completo'] else 2


if __name__ == '__main__':
    raise SystemExit(main())
