#!/usr/bin/env python3
"""Sincronizacao automatica da federacao DNS Shield ISP (executado via cron).

Consulta as listas dos provedores parceiros habilitados, respeitando a
frequencia definida no painel.

Desenvolvedor: Euquias Junior <junior@jbinfo.com.br>
"""
from __future__ import annotations

import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from dnsshield import create_app  # noqa: E402
from dnsshield import federacao  # noqa: E402
from dnsshield import licenca  # noqa: E402


def _due(settings: dict, force: bool) -> bool:
    if force:
        return True
    last = settings.get("ultima_sincronizacao")
    if not last:
        return True
    try:
        parsed = datetime.strptime(last, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
    except (TypeError, ValueError):
        return True
    minutes = max(int(settings.get("frequencia") or 360), 15)
    return datetime.now(timezone.utc) - parsed >= timedelta(minutes=minutes)


def main() -> int:
    force = "--force" in sys.argv
    app = create_app()
    with app.test_request_context():
        if not licenca.modulo_ativo("federacao"):
            print(
                "Federacao nao licenciada; sincronizacao automatica desativada "
                f"({licenca.estado()['motivo']}).",
                file=sys.stderr,
            )
            return 0
        settings = federacao.get_publicacao()
        if not force and not int(settings.get("consumir") or 0):
            print("Federacao (consumo) desabilitada no painel; nada a fazer.")
            return 0
        if not _due(settings, force):
            print("Sincronizacao ainda dentro do intervalo configurado.")
            return 0
        try:
            resultados = federacao.sync_all()
        except federacao.FederacaoError as exc:
            print(f"erro: {exc}", file=sys.stderr)
            return 1
        for item in resultados:
            print(f"{item.nome}: {item.mensagem}")
        return 0


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