"""Чтение журнала вложенного приложения без записи в журнал сборки."""

import os
import selectors
import signal
import subprocess
import time
from dataclasses import dataclass

MAX_LOG_BYTES = 64 * 1024
MAX_SINCE_SECONDS = 7 * 24 * 60 * 60
MAX_TAIL_LINES = 1000
LOG_TIMEOUT_SECONDS = 8


@dataclass(frozen=True)
class LogBudget:
    max_bytes: int
    deadline: float


def application_logs(containers: list[str], query: dict[str, list[str]]) -> dict[str, object]:
    since = log_limit(query, 'since_seconds', 3600, MAX_SINCE_SECONDS)
    tail = log_limit(query, 'tail_lines', 200, MAX_TAIL_LINES)
    entries = []
    remaining = MAX_LOG_BYTES
    deadline = time.monotonic() + LOG_TIMEOUT_SECONDS
    for container in containers:
        command = ['docker', 'logs', '--timestamps', '--since', f'{since}s', '--tail', str(tail), container]
        output, truncated = bounded_output(command, LogBudget(remaining, deadline))
        encoded = output.decode('utf-8', errors='replace').encode('utf-8')
        truncated = truncated or len(encoded) > remaining
        entries.append({'instance': container, 'text': encoded[:remaining].decode('utf-8', errors='ignore'),
                        'truncated': truncated})
        remaining -= min(remaining, len(encoded))
        if truncated or remaining == 0:
            break
    return {'source': 'application', 'logs': entries, 'truncated': remaining == 0 or any(e['truncated'] for e in entries)}


def log_limit(query: dict[str, list[str]], name: str, default: int, maximum: int) -> int:
    values = query.get(name, [str(default)])
    if len(values) != 1:
        raise ValueError(f'{name}: ожидается одно значение')
    limit = int(values[0])
    if not 1 <= limit <= maximum:
        raise ValueError(f'{name}: допустимо от 1 до {maximum}')
    return limit


def bounded_output(command: list[str], budget: LogBudget) -> tuple[bytes, bool]:
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True)
    try:
        with selectors.DefaultSelector() as selector:
            selector.register(process.stdout, selectors.EVENT_READ)
            output = read_output(process, selector, budget)
        return bytes(output[:budget.max_bytes]), len(output) > budget.max_bytes
    finally:
        stop_reader(process)
        process.stdout.close()


def read_output(process: subprocess.Popen, selector: selectors.BaseSelector, budget: LogBudget) -> bytearray:
    output = bytearray()
    limit_bytes, deadline = budget.max_bytes, budget.deadline
    while len(output) <= limit_bytes:
        remaining = deadline - time.monotonic()
        if remaining <= 0 or not selector.select(remaining):
            raise TimeoutError('Чтение журнала приложения превысило время ожидания')
        chunk = os.read(process.stdout.fileno(), min(8192, limit_bytes + 1 - len(output)))
        if not chunk:
            exit_code = process.wait(timeout=max(0.001, deadline - time.monotonic()))
            if exit_code:
                raise subprocess.CalledProcessError(exit_code, process.args)
            break
        output.extend(chunk)
    return output


def stop_reader(process: subprocess.Popen) -> None:
    # Родитель может завершиться раньше дочернего процесса, который ещё держит stdout.
    try:
        os.killpg(process.pid, signal.SIGKILL)
    except ProcessLookupError:
        pass
    process.wait()
