"""Runtime helpers for the repository mesh synchronization cycle.

This module does not replace Git, Gitea, or the operating-system scheduler.  It
provides a deterministic runtime contract for the five-minute synchronization
cycle required by the permanent order:

* acquire a lock before touching mirrors;
* execute only commands that passed repository-mesh safety gates;
* write JSONL receipts for every allowed or blocked command;
* publish scheduler definitions for Windows and Linux;
* keep enough retention metadata for the central service-order database.

The runtime is intentionally conservative.  It is valid for the runtime to
refuse work; it is never valid for it to run an unsafe command silently.
"""

from __future__ import annotations

import json
import os
import subprocess
import time
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any, Iterable, Mapping, Sequence

from .models import GeneratedFile, as_plain_data, merge_unique, utc_now
from .repository_mesh import MeshAction, MeshActionKind, MeshReport, command_is_destructive, rows_to_csv, stable_digest
from .repository_mesh_reconciliation import PlannedOperation, ReconciliationPlan, ReceiptSeverity


class RuntimeCommandStatus(str, Enum):
    """Execution status for one runtime command."""

    ALLOWED = "allowed"
    BLOCKED = "blocked"
    SKIPPED = "skipped"
    EXECUTED = "executed"
    FAILED = "failed"


class RuntimeLockStatus(str, Enum):
    """Lock acquisition status."""

    ACQUIRED = "acquired"
    BUSY = "busy"
    STALE_REPLACED = "stale_replaced"
    RELEASED = "released"
    NOT_HELD = "not_held"


class SchedulerKind(str, Enum):
    """Supported scheduler families."""

    WINDOWS_TASK = "windows_task"
    CRON = "cron"
    SYSTEMD_TIMER = "systemd_timer"
    MANUAL = "manual"


class RuntimeGate(str, Enum):
    """Safety gate names for automatic execution."""

    COMMAND_NOT_DESTRUCTIVE = "command_not_destructive"
    ACTION_MARKED_AUTOMATIC = "action_marked_automatic"
    OPERATION_NOT_DESTRUCTIVE = "operation_not_destructive"
    WORKTREE_POLICY = "worktree_policy"
    CREDENTIAL_POLICY = "credential_policy"
    LOCK_HELD = "lock_held"


@dataclass(frozen=True, slots=True)
class RuntimeLock:
    """Lock metadata for a sync cycle."""

    lock_id: str
    path: str
    status: RuntimeLockStatus
    owner: str
    acquired_at: str | None
    expires_after_seconds: int
    message: str = ""

    @property
    def acquired(self) -> bool:
        return self.status in {RuntimeLockStatus.ACQUIRED, RuntimeLockStatus.STALE_REPLACED}

    def to_dict(self) -> dict[str, Any]:
        return as_plain_data(self)


@dataclass(frozen=True, slots=True)
class RuntimeCommand:
    """One command the runtime may execute or block."""

    command_id: str
    source_id: str
    target_name: str
    command: str
    automatic: bool
    destructive: bool
    gates: tuple[RuntimeGate, ...]
    blocked_reasons: tuple[str, ...]

    @property
    def status(self) -> RuntimeCommandStatus:
        if self.blocked_reasons:
            return RuntimeCommandStatus.BLOCKED
        if not self.automatic:
            return RuntimeCommandStatus.SKIPPED
        return RuntimeCommandStatus.ALLOWED

    def to_dict(self) -> dict[str, Any]:
        return as_plain_data(self)


@dataclass(frozen=True, slots=True)
class RuntimeCommandResult:
    """Result of a runtime command."""

    command: RuntimeCommand
    status: RuntimeCommandStatus
    returncode: int | None = None
    stdout: str = ""
    stderr: str = ""
    started_at: str = field(default_factory=utc_now)
    finished_at: str | None = None

    def to_dict(self) -> dict[str, Any]:
        return as_plain_data(self)


@dataclass(frozen=True, slots=True)
class RuntimeCycle:
    """One repository-mesh runtime cycle."""

    cycle_id: str
    report_id: str
    plan_id: str
    generated_at: str
    lock: RuntimeLock
    commands: tuple[RuntimeCommand, ...]
    results: tuple[RuntimeCommandResult, ...]
    summary: tuple[str, ...]

    @property
    def allowed_count(self) -> int:
        return sum(1 for item in self.commands if item.status == RuntimeCommandStatus.ALLOWED)

    @property
    def blocked_count(self) -> int:
        return sum(1 for item in self.commands if item.status == RuntimeCommandStatus.BLOCKED)

    @property
    def skipped_count(self) -> int:
        return sum(1 for item in self.commands if item.status == RuntimeCommandStatus.SKIPPED)

    def to_dict(self) -> dict[str, Any]:
        return as_plain_data(self)


@dataclass(frozen=True, slots=True)
class SchedulerSpec:
    """Scheduler installation plan."""

    scheduler_id: str
    kind: SchedulerKind
    name: str
    interval_minutes: int
    command: str
    working_directory: str
    environment: tuple[str, ...]
    install_commands: tuple[str, ...]
    uninstall_commands: tuple[str, ...]
    log_path: str
    notes: tuple[str, ...] = ()

    def to_dict(self) -> dict[str, Any]:
        return as_plain_data(self)


def lock_payload(owner: str, expires_after_seconds: int) -> dict[str, Any]:
    return {
        "owner": owner,
        "createdAt": utc_now(),
        "expiresAfterSeconds": expires_after_seconds,
        "pid": os.getpid(),
    }


def read_lock(path: Path) -> Mapping[str, Any] | None:
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None


def lock_is_stale(payload: Mapping[str, Any], now_monotonic: float | None = None) -> bool:
    """Return True when a lock payload should be considered stale.

    The payload uses wall-clock timestamps for auditability.  In tests and in
    degraded environments, malformed timestamps are treated as stale so the
    operator can recover by replacing the lock.
    """

    del now_monotonic
    created = str(payload.get("createdAt", ""))
    expires = int(payload.get("expiresAfterSeconds", 0) or 0)
    if expires <= 0:
        return True
    pid = payload.get("pid")
    if isinstance(pid, int) and pid > 0 and pid != os.getpid() and not process_is_alive(pid):
        return True
    try:
        from datetime import datetime

        created_dt = datetime.fromisoformat(created.replace("Z", "+00:00"))
        age = time.time() - created_dt.timestamp()
        return age > expires
    except (ValueError, TypeError, OSError):
        return True


def process_is_alive(pid: int) -> bool:
    """Return whether a local process id is still alive without killing it."""

    if pid <= 0:
        return False
    if os.name == "nt":
        try:
            result = subprocess.run(
                ["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"],
                check=False,
                capture_output=True,
                text=True,
                timeout=5,
            )
        except (OSError, subprocess.SubprocessError):
            return True
        return str(pid) in result.stdout
    try:
        os.kill(pid, 0)
        return True
    except ProcessLookupError:
        return False
    except PermissionError:
        return True
    except OSError:
        return False


def acquire_lock(path: Path, *, owner: str, expires_after_seconds: int = 600) -> RuntimeLock:
    """Acquire a JSON lock file without deleting non-stale locks."""

    path.parent.mkdir(parents=True, exist_ok=True)
    payload = lock_payload(owner, expires_after_seconds)
    if path.exists():
        current = read_lock(path)
        if current and not lock_is_stale(current):
            return RuntimeLock(
                lock_id=f"mesh-lock-{stable_digest(current, 12)}",
                path=str(path),
                status=RuntimeLockStatus.BUSY,
                owner=str(current.get("owner", "unknown")),
                acquired_at=str(current.get("createdAt", "")),
                expires_after_seconds=int(current.get("expiresAfterSeconds", expires_after_seconds) or expires_after_seconds),
                message="lock existente ainda valido",
            )
        path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
        return RuntimeLock(
            lock_id=f"mesh-lock-{stable_digest(payload, 12)}",
            path=str(path),
            status=RuntimeLockStatus.STALE_REPLACED,
            owner=owner,
            acquired_at=str(payload["createdAt"]),
            expires_after_seconds=expires_after_seconds,
            message="lock antigo estava ausente, invalido ou expirado",
        )
    try:
        with path.open("x", encoding="utf-8") as handle:
            json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True)
        return RuntimeLock(
            lock_id=f"mesh-lock-{stable_digest(payload, 12)}",
            path=str(path),
            status=RuntimeLockStatus.ACQUIRED,
            owner=owner,
            acquired_at=str(payload["createdAt"]),
            expires_after_seconds=expires_after_seconds,
            message="lock adquirido",
        )
    except FileExistsError:
        return RuntimeLock(
            lock_id=f"mesh-lock-{stable_digest({'path': str(path), 'owner': owner}, 12)}",
            path=str(path),
            status=RuntimeLockStatus.BUSY,
            owner=owner,
            acquired_at=None,
            expires_after_seconds=expires_after_seconds,
            message="lock criado por outro processo durante aquisicao",
        )


def release_lock(lock: RuntimeLock) -> RuntimeLock:
    path = Path(lock.path)
    if not lock.acquired:
        return RuntimeLock(
            lock_id=lock.lock_id,
            path=lock.path,
            status=RuntimeLockStatus.NOT_HELD,
            owner=lock.owner,
            acquired_at=lock.acquired_at,
            expires_after_seconds=lock.expires_after_seconds,
            message="lock nao estava em posse deste ciclo",
        )
    try:
        path.unlink(missing_ok=True)
        return RuntimeLock(
            lock_id=lock.lock_id,
            path=lock.path,
            status=RuntimeLockStatus.RELEASED,
            owner=lock.owner,
            acquired_at=lock.acquired_at,
            expires_after_seconds=lock.expires_after_seconds,
            message="lock liberado",
        )
    except OSError as exc:
        return RuntimeLock(
            lock_id=lock.lock_id,
            path=lock.path,
            status=RuntimeLockStatus.BUSY,
            owner=lock.owner,
            acquired_at=lock.acquired_at,
            expires_after_seconds=lock.expires_after_seconds,
            message=f"falha ao liberar lock: {exc}",
        )


def runtime_command_id(source_id: str, target_name: str, command: str) -> str:
    return f"mesh-cmd-{stable_digest({'source': source_id, 'target': target_name, 'command': command}, 12)}"


def command_from_action(action: MeshAction) -> tuple[RuntimeCommand, ...]:
    commands: list[RuntimeCommand] = []
    previews = action.command_preview or (f"NOOP action:{action.kind.value}",)
    for command in previews:
        blocked: list[str] = []
        gates = [RuntimeGate.COMMAND_NOT_DESTRUCTIVE]
        destructive = command_is_destructive(command) or action.destructive
        if destructive:
            blocked.append("comando ou acao marcado como destrutivo")
        if not action.can_execute_automatically:
            blocked.append("acao nao marcada como automatica")
        else:
            gates.append(RuntimeGate.ACTION_MARKED_AUTOMATIC)
        commands.append(
            RuntimeCommand(
                command_id=runtime_command_id(action.action_id, action.target_name, command),
                source_id=action.action_id,
                target_name=action.target_name,
                command=command,
                automatic=action.can_execute_automatically,
                destructive=destructive,
                gates=tuple(gates),
                blocked_reasons=tuple(blocked),
            )
        )
    return tuple(commands)


def command_from_operation(operation: PlannedOperation) -> tuple[RuntimeCommand, ...]:
    commands: list[RuntimeCommand] = []
    previews = operation.commands or (f"NOOP operation:{operation.status.value}",)
    for command in previews:
        blocked: list[str] = []
        gates = [RuntimeGate.COMMAND_NOT_DESTRUCTIVE]
        destructive = command_is_destructive(command) or operation.destructive
        if destructive:
            blocked.append("comando ou operacao marcado como destrutivo")
        if operation.severity == ReceiptSeverity.BLOCKER:
            blocked.append("operacao possui severidade blocker")
        if not operation.automatic:
            blocked.append("operacao requer execucao manual")
        else:
            gates.append(RuntimeGate.OPERATION_NOT_DESTRUCTIVE)
        commands.append(
            RuntimeCommand(
                command_id=runtime_command_id(operation.operation_id, operation.target_name, command),
                source_id=operation.operation_id,
                target_name=operation.target_name,
                command=command,
                automatic=operation.automatic,
                destructive=destructive,
                gates=tuple(gates),
                blocked_reasons=tuple(blocked),
            )
        )
    return tuple(commands)


def commands_from_report_and_plan(report: MeshReport, plan: ReconciliationPlan) -> tuple[RuntimeCommand, ...]:
    commands: list[RuntimeCommand] = []
    for summary in report.summaries:
        for action in summary.actions:
            commands.extend(command_from_action(action))
    for receipt in plan.receipts:
        for operation in receipt.operations:
            commands.extend(command_from_operation(operation))
    dedup: dict[str, RuntimeCommand] = {}
    for command in commands:
        dedup.setdefault(command.command_id, command)
    return tuple(dedup.values())


def build_runtime_cycle(
    report: MeshReport,
    plan: ReconciliationPlan,
    *,
    lock: RuntimeLock,
    execute: bool = False,
) -> RuntimeCycle:
    """Build a runtime cycle receipt.

    ``execute`` is intentionally present but not used to shell out in this
    module.  A future runner can replace the result construction with an actual
    subprocess layer after preserving the same gates.
    """

    commands = commands_from_report_and_plan(report, plan)
    results: list[RuntimeCommandResult] = []
    for command in commands:
        status = command.status
        if not lock.acquired:
            status = RuntimeCommandStatus.BLOCKED
            command = RuntimeCommand(
                command_id=command.command_id,
                source_id=command.source_id,
                target_name=command.target_name,
                command=command.command,
                automatic=command.automatic,
                destructive=command.destructive,
                gates=command.gates,
                blocked_reasons=merge_unique((*command.blocked_reasons, "lock nao adquirido")),
            )
        elif execute and command.status == RuntimeCommandStatus.ALLOWED:
            status = RuntimeCommandStatus.SKIPPED
        results.append(RuntimeCommandResult(command=command, status=status, finished_at=utc_now()))
    summary = (
        f"commands: {len(commands)}",
        f"allowed: {sum(1 for item in commands if item.status == RuntimeCommandStatus.ALLOWED)}",
        f"blocked: {sum(1 for item in commands if item.status == RuntimeCommandStatus.BLOCKED)}",
        f"skipped: {sum(1 for item in commands if item.status == RuntimeCommandStatus.SKIPPED)}",
        f"lock: {lock.status.value}",
    )
    seed = {"report": report.report_id, "plan": plan.plan_id, "lock": lock.lock_id, "commands": [cmd.command_id for cmd in commands]}
    return RuntimeCycle(
        cycle_id=f"mesh-cycle-{stable_digest(seed, 12)}",
        report_id=report.report_id,
        plan_id=plan.plan_id,
        generated_at=utc_now(),
        lock=lock,
        commands=commands,
        results=tuple(results),
        summary=summary,
    )


def runtime_rows(cycle: RuntimeCycle) -> list[list[str]]:
    rows = [["command_id", "target_name", "status", "automatic", "destructive", "command", "blocked_reasons"]]
    for result in cycle.results:
        command = result.command
        rows.append(
            [
                command.command_id,
                command.target_name,
                result.status.value,
                "yes" if command.automatic else "no",
                "yes" if command.destructive else "no",
                command.command,
                " | ".join(command.blocked_reasons),
            ]
        )
    return rows


def runtime_csv(cycle: RuntimeCycle) -> str:
    return rows_to_csv(runtime_rows(cycle))


def runtime_jsonl(cycle: RuntimeCycle) -> str:
    lines = [json.dumps(as_plain_data(result), ensure_ascii=False, sort_keys=True) for result in cycle.results]
    return "\n".join(lines) + ("\n" if lines else "")


def runtime_markdown(cycle: RuntimeCycle) -> str:
    lines = [
        "# Repository Mesh Runtime Cycle",
        "",
        f"- cycle_id: `{cycle.cycle_id}`",
        f"- report_id: `{cycle.report_id}`",
        f"- plan_id: `{cycle.plan_id}`",
        f"- generated_at: `{cycle.generated_at}`",
        f"- lock_status: `{cycle.lock.status.value}`",
        f"- allowed: `{cycle.allowed_count}`",
        f"- blocked: `{cycle.blocked_count}`",
        f"- skipped: `{cycle.skipped_count}`",
        "",
        "## Sumario",
        "",
    ]
    lines.extend(f"- {item}" for item in cycle.summary)
    lines.extend(["", "## Comandos", ""])
    for result in cycle.results[:160]:
        command = result.command
        lines.append(f"- `{result.status.value}` `{command.target_name}` `{command.command}`")
        if command.blocked_reasons:
            lines.append(f"  - bloqueios: {'; '.join(command.blocked_reasons)}")
    return "\n".join(lines).strip() + "\n"


def windows_scheduler_spec(
    *,
    python_exe: str,
    project_root: Path,
    ecosystem_root: Path,
    central_platform_folder: Path | None,
    interval_minutes: int = 5,
) -> SchedulerSpec:
    central_arg = f" --central-platform-folder '{central_platform_folder}'" if central_platform_folder else ""
    command = (
        f"'{python_exe}' -m mais_humana.cli repo-mesh --ecosystem-root '{ecosystem_root}' "
        f"--project-root '{project_root}'{central_arg} --fetch"
    )
    task_name = "TudoParaIA-RepositoryMeshSync"
    install = (
        f"$Action = New-ScheduledTaskAction -Execute '{python_exe}' -Argument \"-m mais_humana.cli repo-mesh --ecosystem-root '{ecosystem_root}' --project-root '{project_root}'{central_arg} --fetch\"",
        f"$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes {interval_minutes})",
        f"Register-ScheduledTask -TaskName '{task_name}' -Action $Action -Trigger $Trigger",
    )
    return SchedulerSpec(
        scheduler_id=f"scheduler-{stable_digest({'kind': 'windows', 'project': str(project_root)}, 10)}",
        kind=SchedulerKind.WINDOWS_TASK,
        name=task_name,
        interval_minutes=interval_minutes,
        command=command,
        working_directory=str(project_root),
        environment=(f"PYTHONPATH={project_root / 'src'}",),
        install_commands=install,
        uninstall_commands=(f"Unregister-ScheduledTask -TaskName '{task_name}' -Confirm:$false",),
        log_path=str(project_root / "dados" / "repository-mesh-runtime.jsonl"),
        notes=("usar credencial Git do usuario operacional", "nao usar plugin Cloudflare como via de sincronizacao"),
    )


def cron_scheduler_spec(
    *,
    python_exe: str,
    project_root: Path,
    ecosystem_root: Path,
    central_platform_folder: Path | None = None,
    interval_minutes: int = 5,
) -> SchedulerSpec:
    central_arg = f" --central-platform-folder '{central_platform_folder}'" if central_platform_folder else ""
    command = (
        f"cd '{project_root}' && PYTHONPATH='{project_root / 'src'}' '{python_exe}' "
        f"-m mais_humana.cli repo-mesh --ecosystem-root '{ecosystem_root}' --project-root '{project_root}'{central_arg} --fetch"
    )
    cron_line = f"*/{interval_minutes} * * * * {command} >> '{project_root / 'dados' / 'repository-mesh-cron.log'}' 2>&1"
    return SchedulerSpec(
        scheduler_id=f"scheduler-{stable_digest({'kind': 'cron', 'project': str(project_root)}, 10)}",
        kind=SchedulerKind.CRON,
        name="tudo-para-ia-repository-mesh-sync",
        interval_minutes=interval_minutes,
        command=command,
        working_directory=str(project_root),
        environment=(f"PYTHONPATH={project_root / 'src'}",),
        install_commands=(f"(crontab -l; echo \"{cron_line}\") | crontab -",),
        uninstall_commands=("crontab -l | grep -v 'repository-mesh' | crontab -",),
        log_path=str(project_root / "dados" / "repository-mesh-cron.log"),
        notes=("executar em cada host Linux da malha", "bloquear se houver dirty tree ou divergencia"),
    )


def scheduler_payload(specs: Sequence[SchedulerSpec]) -> dict[str, Any]:
    return {
        "generatedAt": utc_now(),
        "schedulers": [spec.to_dict() for spec in specs],
        "intervalMinutes": merge_unique(str(spec.interval_minutes) for spec in specs),
        "kinds": merge_unique(spec.kind.value for spec in specs),
    }


def scheduler_markdown(specs: Sequence[SchedulerSpec]) -> str:
    lines = ["# Repository Mesh Scheduler Specs", ""]
    for spec in specs:
        lines.append(f"## {spec.name}")
        lines.append("")
        lines.append(f"- kind: `{spec.kind.value}`")
        lines.append(f"- interval_minutes: `{spec.interval_minutes}`")
        lines.append(f"- working_directory: `{spec.working_directory}`")
        lines.append(f"- log_path: `{spec.log_path}`")
        lines.append("")
        lines.append("Install:")
        for command in spec.install_commands:
            lines.append(f"- `{command}`")
        lines.append("")
        lines.append("Uninstall:")
        for command in spec.uninstall_commands:
            lines.append(f"- `{command}`")
        if spec.notes:
            lines.append("")
            lines.append("Notas:")
            for note in spec.notes:
                lines.append(f"- {note}")
        lines.append("")
    return "\n".join(lines).strip() + "\n"


def write_json(path: Path, payload: object) -> Path:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(as_plain_data(payload), ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
    return path


def write_text(path: Path, text: str) -> Path:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")
    return path


def write_runtime_artifacts(
    cycle: RuntimeCycle,
    specs: Sequence[SchedulerSpec],
    project_root: Path,
    *,
    central_platform_folder: Path | None = None,
) -> tuple[GeneratedFile, ...]:
    write_json(project_root / "dados" / "repository-mesh-runtime-cycle.json", cycle)
    write_text(project_root / "dados" / "repository-mesh-runtime.jsonl", runtime_jsonl(cycle))
    write_text(project_root / "matrizes" / "repository-mesh-runtime.csv", runtime_csv(cycle))
    write_json(project_root / "dados" / "repository-mesh-schedulers.json", scheduler_payload(specs))
    write_text(project_root / "ecossistema" / "REPOSITORY-MESH-RUNTIME.md", runtime_markdown(cycle))
    write_text(project_root / "ecossistema" / "REPOSITORY-MESH-SCHEDULERS.md", scheduler_markdown(specs))
    central_written: list[Path] = []
    if central_platform_folder is not None:
        path = central_platform_folder / "reports" / "EXECUTADO__repository-mesh-runtime.md"
        try:
            write_text(path, runtime_markdown(cycle))
        except OSError:
            pass
        else:
            central_written.append(path)
    records = [
        GeneratedFile(
            path="dados/repository-mesh-runtime-cycle.json",
            description="Recibo JSON do ciclo runtime da malha.",
            function="repository mesh runtime",
            file_type="json",
            changed_by="mais_humana.repository_mesh_runtime",
            change_summary="Criado recibo de comandos permitidos/bloqueados.",
            relation_to_order="000_sincronizacao-dos-espelhos",
        ),
        GeneratedFile(
            path="dados/repository-mesh-runtime.jsonl",
            description="Log JSONL dos comandos do ciclo runtime.",
            function="repository mesh runtime log",
            file_type="jsonl",
            changed_by="mais_humana.repository_mesh_runtime",
            change_summary="Criado log JSONL auditavel.",
            relation_to_order="000_sincronizacao-dos-espelhos",
        ),
        GeneratedFile(
            path="matrizes/repository-mesh-runtime.csv",
            description="Matriz dos comandos do runtime.",
            function="repository mesh runtime matrix",
            file_type="csv",
            changed_by="mais_humana.repository_mesh_runtime",
            change_summary="Criada matriz de comandos permitidos/bloqueados.",
            relation_to_order="000_sincronizacao-dos-espelhos",
        ),
        GeneratedFile(
            path="dados/repository-mesh-schedulers.json",
            description="Especificacoes de agendamento da malha.",
            function="repository mesh scheduler",
            file_type="json",
            changed_by="mais_humana.repository_mesh_runtime",
            change_summary="Criadas especificacoes Windows/Cron.",
            relation_to_order="000_sincronizacao-dos-espelhos",
        ),
        GeneratedFile(
            path="ecossistema/REPOSITORY-MESH-RUNTIME.md",
            description="Relatorio humano do ciclo runtime.",
            function="repository mesh runtime report",
            file_type="markdown",
            changed_by="mais_humana.repository_mesh_runtime",
            change_summary="Documentado ciclo runtime seguro.",
            relation_to_order="000_sincronizacao-dos-espelhos",
        ),
        GeneratedFile(
            path="ecossistema/REPOSITORY-MESH-SCHEDULERS.md",
            description="Instalacao sugerida dos schedulers da malha.",
            function="repository mesh scheduler report",
            file_type="markdown",
            changed_by="mais_humana.repository_mesh_runtime",
            change_summary="Documentado scheduler de 5 minutos.",
            relation_to_order="000_sincronizacao-dos-espelhos",
        ),
    ]
    for central_path in central_written:
        records.append(
            GeneratedFile(
                path=str(central_path),
                description="Runtime registrado na central.",
                function="repository mesh central runtime",
                file_type="markdown",
                changed_by="mais_humana.repository_mesh_runtime",
                change_summary="Registrado runtime da sincronizacao na central.",
                relation_to_order="000_sincronizacao-dos-espelhos",
            )
        )
    return tuple(records)
