"""Prospective C3-S supervisor with affirmative tracked-PID absence checks.

The v1 supervisor and both report launchers are frozen. This module shares
the existing clock, process and receipt helpers and qualifies a separate
lifecycle without any report entry point.
"""

import hashlib
import os
import selectors
import signal
import subprocess
import time

from pf002_c3_completion_supervisor_v1 import (
    STREAM_CAP, TOTAL_DEADLINE, SupervisorSignal, _LIVE_HANDLES, _descendants,
    _pid_start, _ps_table, _retain_publication_failure, _retain_receipt, _scan_snapshot,
)


def _identity_snapshot(clock):
    """Take a complete, parseable process snapshot for affirmative absence."""
    result = subprocess.run(
        ["ps", "-A", "-o", "pid=,lstart="], capture_output=True, text=True,
        timeout=clock.timeout(2.0), check=True)
    if result.stderr or not result.stdout.strip():
        raise ValueError("process_snapshot_incomplete")
    identities = {}
    for line in result.stdout.splitlines():
        pid_text, start = line.split(maxsplit=1)
        pid = int(pid_text)
        if pid <= 0 or pid in identities or not start.strip():
            raise ValueError("process_snapshot_identity")
        identities[pid] = start.strip()
    # A successful command that omitted our own live PID cannot certify
    # the absence of anyone else.
    if os.getpid() not in identities:
        raise ValueError("process_snapshot_missing_self")
    return identities


def _confirm_absence(pid, clock):
    try:
        clock.timeout(2.0)
        os.kill(pid, 0)
    except ProcessLookupError:
        return "verified_absent"
    except PermissionError:
        return "absence_probe_denied"
    except TimeoutError:
        return "absence_probe_deadline"
    return "absence_probe_found_pid"


def _signal_tracked(pid, clock):
    try:
        clock.timeout(2.0)
        os.kill(pid, signal.SIGKILL)
    except ProcessLookupError:
        # The identity was just verified and the syscall found no PID.
        return "disappeared_before_signal"
    except PermissionError:
        return "signal_denied"
    except TimeoutError:
        return "signal_deadline"
    return "signal_sent"


def _tracked_disposition(pid, saved, snapshot, clock):
    if not saved:
        return "missing_tracked_identity"
    if pid not in snapshot:
        return _confirm_absence(pid, clock)
    if snapshot[pid] != saved:
        return "identity_mismatch"
    # A complete recheck distinguishes a missing PID from an unreadable
    # lookup. Reused identities never reach either signal path.
    try:
        latest = _identity_snapshot(clock)
    except (OSError, ValueError, subprocess.SubprocessError):
        return "identity_recheck_unavailable"
    if pid not in latest:
        return _confirm_absence(pid, clock)
    if latest[pid] != saved:
        return "identity_recheck_failed"
    return _signal_tracked(pid, clock)


def _cleanup_tracked(tracked, saved, clock):
    """Classify owned descendants without treating an unknown PID as absent."""
    if not tracked:
        return {}, []
    try:
        snapshot = _identity_snapshot(clock)
    except (OSError, ValueError, subprocess.SubprocessError) as error:
        return ({str(pid): "scan_unavailable" for pid in sorted(tracked)},
                [f"tracked_cleanup_scan:{type(error).__name__}"])
    dispositions = {str(pid): _tracked_disposition(pid, saved.get(pid), snapshot, clock)
                    for pid in sorted(tracked)}
    cleared = {"verified_absent", "disappeared_before_signal", "signal_sent"}
    errors = [f"tracked_cleanup:{pid}:{state}" for pid, state in dispositions.items()
              if state not in cleared]
    return dispositions, errors


def supervise(argv, cwd, out_dir, record, clock, reserve=2.0,
              cap=STREAM_CAP, postflight=None):
    """Supervise one child; cleanup and receipts are unconditional."""
    record["success"] = False
    record["deadline_exceeded"] = False
    record["supervisor_pid"] = os.getpid()
    record["supervisor_ppid"] = os.getppid()
    buffers = {"stdout": bytearray(), "stderr": bytearray()}
    exceeded, tracked = set(), set()
    tracked_identities = {}
    child = None
    previous_handlers = {}
    finalizing = False
    termination = None

    def _handler(signum, _frame):
        nonlocal termination
        if finalizing:
            if termination is None:
                termination = signum
            return
        raise SupervisorSignal(signum)

    can_signal = hasattr(signal, "SIGTERM")
    if can_signal:
        for sig in (signal.SIGTERM, signal.SIGINT,
                    getattr(signal, "SIGHUP", signal.SIGTERM)):
            try:
                previous_handlers[sig] = signal.signal(sig, _handler)
            except (ValueError, OSError):
                pass
    try:
        if clock.remaining() <= reserve:
            record["stop_reason"] = "deadline"
            return record
        try:
            child = subprocess.Popen(
                argv, cwd=cwd, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, stdin=subprocess.DEVNULL,
                start_new_session=True)
        except Exception as error:
            record["stop_reason"] = "launch_exception"
            record["launch_exception"] = type(error).__name__
            return record
        _LIVE_HANDLES[child.pid] = child
        record["child_pid"] = child.pid
        record["child_pgid"] = os.getpgid(child.pid)
        record["child_start_identity"] = _pid_start(child.pid, clock, reserve)
        record["child_start_utc"] = time.strftime(
            "%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        selector = selectors.DefaultSelector()
        selector.register(child.stdout, selectors.EVENT_READ, "stdout")
        selector.register(child.stderr, selectors.EVENT_READ, "stderr")
        record["stop_reason"] = "interrupted"
        try:
            while selector.get_map():
                left = clock.remaining() - reserve
                if left <= 0:
                    record["stop_reason"] = "deadline"
                    break
                events = selector.select(timeout=min(left, 0.1))
                try:
                    snap = _scan_snapshot(clock, reserve)
                    rows = [(pid, v["ppid"], v["pgid"])
                            for pid, v in snap.items()]
                    found = _descendants(rows, child.pid)
                    for pid in found:
                        if pid not in tracked_identities:
                            tracked_identities[pid] = snap[pid]["start"]
                    tracked |= found
                except (TimeoutError, subprocess.TimeoutExpired):
                    record["stop_reason"] = "deadline"
                    break
                except Exception:
                    record["scan_error"] = True
                if clock.remaining() <= reserve:
                    record["stop_reason"] = "deadline"
                    break
                for key, _ in events:
                    chunk = os.read(key.fileobj.fileno(), 65536)
                    if not chunk:
                        selector.unregister(key.fileobj)
                        continue
                    room = cap - len(buffers[key.data])
                    buffers[key.data] += chunk[:room]
                    if len(chunk) > room:
                        exceeded.add(key.data)
                        record["stop_reason"] = "stream_cap"
                if record["stop_reason"] == "stream_cap":
                    break
            else:
                record["stop_reason"] = "eof"
        finally:
            selector.close()
        if record.get("stop_reason") == "eof":
            try:
                child.wait(timeout=clock.timeout(TOTAL_DEADLINE, reserve))
            except (TimeoutError, subprocess.TimeoutExpired):
                record["stop_reason"] = "deadline"
        return record
    except SupervisorSignal as error:
        record.update(stop_reason="signal", signal=error.signum)
        raise
    finally:
        # Keep cleanup non-interruptible at the Python level, while
        # recording termination delivered during cleanup or postflight.
        finalizing = True
        try:
            record["tracked_descendants"] = sorted(tracked)
            record["tracked_identities"] = {
                str(k): v for k, v in sorted(tracked_identities.items())}
            cleanup_errors = []
            record["tracked_cleanup_dispositions"] = {}
            if record.get("scan_error"):
                cleanup_errors.append("scan_drain")
            if child is not None:
                dispositions, problems = _cleanup_tracked(tracked, tracked_identities, clock)
                record["tracked_cleanup_dispositions"] = dispositions
                cleanup_errors.extend(problems)
                # Kill the group only while the leader is alive or a
                # scan shows live members of its group; after the leader
                # is reaped the PGID may have been reused, so an absent
                # leader with no scanned members is verified absence.
                members = []
                snap = {}
                try:
                    snap = _scan_snapshot(clock)
                    members = [pid for pid, v in snap.items()
                               if v["pgid"] == child.pid
                               and pid != child.pid]
                except Exception:
                    cleanup_errors.append("scan_cleanup")
                leader_alive = child.poll() is None
                # membership and start identity from the same snapshot
                verified_members = [
                    pid for pid in members
                    if tracked_identities.get(pid) is not None
                    and snap[pid]["start"] == tracked_identities[pid]]
                if leader_alive:
                    # our unreaped direct child: its PID is still ours
                    should_kill_group = True
                elif verified_members:
                    should_kill_group = True
                elif members:
                    should_kill_group = False
                    cleanup_errors.append("group_ownership_uncertain")
                else:
                    should_kill_group = False  # verified absence
                if should_kill_group:
                    try:
                        os.killpg(child.pid, signal.SIGKILL)
                    except ProcessLookupError:
                        if leader_alive:
                            cleanup_errors.append(
                                "group_absence_unverified")
                    except PermissionError as error:
                        cleanup_errors.append(
                            f"group_denial:{type(error).__name__}")
                try:
                    child.wait(timeout=max(0.0, min(5.0,
                                                     clock.remaining())))
                    record["reaped"] = True
                    _LIVE_HANDLES.pop(child.pid, None)
                except subprocess.TimeoutExpired:
                    record["reaped"] = False
                    record["child_handle_retained"] = True
                    cleanup_errors.append("reap_timeout")
                for stream in (child.stdout, child.stderr):
                    if stream:
                        stream.close()
                record["exit"] = child.returncode
            try:
                rows = _ps_table(clock)
                live = _descendants(rows, child.pid) if child else set()
                live |= {pid for pid, _, pgid in rows
                         if child and pgid == child.pid
                         and pid != child.pid}
                for pid in list(tracked):
                    try:
                        os.kill(pid, 0)
                        live.add(pid)
                    except ProcessLookupError:
                        pass
                    except PermissionError:
                        live.add(pid)  # exists but not signalable
                live -= {os.getpid()}
                record["survivors_by_ps"] = "none_found" if not live \
                    else f"survivors_found:{sorted(live)}"
                if live:
                    cleanup_errors.append("survivors")
            except Exception:
                record["survivors_by_ps"] = "unavailable"
                cleanup_errors.append("scan")
            record["cleanup_errors"] = cleanup_errors
            record["cleanup_ok"] = not cleanup_errors
            record["child_end_utc"] = time.strftime(
                "%Y-%m-%dT%H:%M:%SZ", time.gmtime())
            log_ok = True
            for name in ("stdout", "stderr"):
                data = bytes(buffers[name])
                try:
                    with open(os.path.join(out_dir, f"{name}.log"),
                              "xb") as stream:
                        stream.write(data)
                    record[name] = {
                        "bytes": len(data),
                        "sha256": hashlib.sha256(data).hexdigest(),
                        "exceeded_cap": name in exceeded}
                except Exception as error:
                    record[name] = {"error": type(error).__name__}
                    log_ok = False
            record["child_success"] = bool(
                child is not None and record.get("stop_reason") == "eof"
                and record.get("exit") == 0 and record.get("reaped")
                and record["cleanup_ok"] and log_ok and not exceeded
                and record["survivors_by_ps"] == "none_found")
            if postflight is not None and "signal" not in record and termination is None:
                try:
                    clock.timeout(TOTAL_DEADLINE)
                    record["after"] = postflight(clock)
                    clock.timeout(TOTAL_DEADLINE)
                    if not record["after"]["before_after_match"]:
                        record["postflight_error"] = "postflight_drift"
                except SupervisorSignal as error:
                    termination = error.signum
                except (TimeoutError, subprocess.TimeoutExpired):
                    record["postflight_error"] = "postflight_deadline"
                except Exception as error:
                    record["postflight_error"] = type(error).__name__
            if termination is not None:
                record.update(stop_reason="signal", signal=termination)
            record["deadline_exceeded"] = clock.remaining() <= 0
            record["success"] = bool(
                record["child_success"] and not record["deadline_exceeded"]
                and not record.get("postflight_error") and "signal" not in record)
            signal_at_publication = record.get("signal")
            _retain_receipt(out_dir, record, clock)
        finally:
            for sig, handler in previous_handlers.items():
                try:
                    signal.signal(sig, handler)
                except (ValueError, OSError):
                    pass
        if termination is not None:
            record.update(stop_reason="signal", signal=termination, success=False)
        record["deadline_exceeded"] |= clock.remaining() <= 0
        if record["deadline_exceeded"]:
            record["success"] = False
        if record["receipt_retained"] and (
                record.get("receipt_deadline_exceeded")
                or record.get("signal") != signal_at_publication
                or (record["receipt_state"] == "provisional" and not record["success"])):
            _retain_publication_failure(out_dir, record)
        if termination is not None:
            raise SupervisorSignal(termination)
