# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
"""Serve logs process."""

from __future__ import annotations

import socket
import sys

import structlog
import uvicorn

from airflow.configuration import conf

logger = structlog.get_logger(__name__)


def serve_logs(port=None):
    """Serve logs generated by Worker."""
    # setproctitle causes issue on Mac OS: https://github.com/benoitc/gunicorn/issues/3021
    os_type = sys.platform
    if os_type == "darwin":
        logger.debug("Mac OS detected, skipping setproctitle")
    else:
        from setproctitle import setproctitle

        setproctitle("airflow serve-logs")

    port = port or conf.getint("logging", "WORKER_LOG_SERVER_PORT")

    if socket.has_dualstack_ipv6():
        serve_log_uri = f"http://[::]:{port}"
    else:
        serve_log_uri = f"http://0.0.0.0:{port}"

    logger.info("Starting log server on %s", serve_log_uri)

    # Get uvicorn logging configuration from Airflow settings
    uvicorn_log_level = conf.get("logging", "uvicorn_logging_level", fallback="info").lower()

    # Use uvicorn directly for ASGI applications.
    # log_config=None: preserve the process's structlog-based logging setup rather than
    # letting uvicorn reset it with its own default formatter.
    # access_log=False: the log server serves internal file content; HTTP access logs
    # are not needed and would be non-JSON noise when json_logs=True.
    uvicorn.run(
        "airflow.utils.serve_logs.log_server:get_app",
        host="",
        port=port,
        log_level=uvicorn_log_level,
        log_config=None,
        access_log=False,
    )
    # Log serving is I/O bound and has low concurrency, so single process is sufficient


if __name__ == "__main__":
    serve_logs()
