import argparse

from falcorn import PLUGIN_FILTER_ALL, LoggingClient


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Falcorn logging plugin client (SDK)")
    parser.add_argument("--socket", default=None, help="Log socket path")
    parser.add_argument("--token", default=None, help="Auth token")
    parser.add_argument("--client-name", default=None, help="Client name")
    parser.add_argument(
        "--filter-mask",
        default=PLUGIN_FILTER_ALL,
        type=int,
        help="Filter mask (default: PLUGIN_FILTER_ALL)",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    client = LoggingClient(
        socket=args.socket,
        auth_token=args.token,
        client_name=args.client_name,
        filter_mask=args.filter_mask,
    )

    while True:
        event = client.next_event()
        event_type = event.get("type")
        if event_type == "log":
            print(
                f"[{event['ts_millis']}] {event['level']} pid={event['pid']} worker={event['worker_id']} - {event['message']}"
            )
        elif event_type == "access":
            print(
                f"[{event['ts_millis']}] {event['remote']} {event['method']} {event['uri']} "
                f"status={event['status']} {event['duration_micros']}us"
            )
        elif event_type == "metrics":
            print(
                f"METRICS rps={event['requests_per_second']:.2f} "
                f"success_rate={event['success_rate']:.4f} "
                f"avg_us={event['avg_response_time_micros']} "
                f"active_conn={event['active_connections']}"
            )


if __name__ == "__main__":
    main()
