"""Concrete r71b maintenance file lifecycle contracts."""

from __future__ import annotations

import json
from datetime import date, datetime
from pathlib import Path

from gateway.platforms.nutrition_weekly_maintenance_contract import Topic59MaintenanceScopeV1
from scripts.nutricoach_v150_r71b_maintenance_host import (
    R71bMaintenanceFiles,
    R71bMaintenancePaths,
)
from scripts.nutricoach_v150_r71b_package import derive_r71b_package
from scripts.nutricoach_v150_sealed_target import DisposableService


def _artifacts():
    scope = Topic59MaintenanceScopeV1(
        candidate_digest="1" * 64,
        config_digest="2" * 64,
        route_digest="3" * 64,
        customer_identity_digest="4" * 64,
        card_slot="5" * 64,
        kst_day=date(2026, 9, 1),
        not_before=datetime.fromisoformat("2026-09-01T16:00:00+09:00"),
        expires_at=datetime.fromisoformat("2026-09-01T16:10:00+09:00"),
    )
    binding = {
        "schema": "nutricoach-v150-r71b-package-binding-inputs-v1",
        "product_generation": "r71",
        "package_namespace": "r71b-maintenance",
        "authority_id": "nutricoach-v150-v15-runtime-authority-r71b-maintenance",
        "paths": {"observer_root": "/tmp/observer-r71"},
        "candidate": {"candidate_digest": "1" * 64},
        "wheels": [],
        "controller": {"files": {}},
        "protected_inventory": {"explicit_maintenance_volatile_paths": []},
        "dependency_snapshot": {"dependency_snapshot_sha256": "6" * 64},
        "authority_baseline": {"candidate_digest": "7" * 64},
        "target_binding_base": {"profile_root": "/tmp/profile"},
        "service_preparation": {"ActiveState": "active"},
        "maintenance_scope": scope.model_dump(mode="json", by_alias=True),
        "maintenance_scope_path": "maintenance/maintenance-scope.json",
        "maintenance_scope_file_sha256": "8" * 64,
        "maintenance_scope_digest": "9" * 64,
        "no_send_oracle": {"schema": "nutricoach-r71b-no-send-oracle-v1"},
        "no_send_oracle_path": "maintenance/no-send-oracle.json",
        "no_send_oracle_file_sha256": "a" * 64,
        "diagnosed_blocker_evidence": [],
    }
    return derive_r71b_package(binding, scope)


def test_hold_and_credential_are_exact_then_rollback_pauses_cron(tmp_path: Path) -> None:
    # Given
    artifacts = _artifacts()
    profile = tmp_path / "profile"
    cron = profile / "cron/jobs.json"
    cron.parent.mkdir(parents=True)
    original = {
        "jobs": [{
            "id": "6e042d5dff68",
            "name": "NutriCoach schedule dispatcher",
            "schedule_display": "* * * * *",
            "inline_card": "nutrition-coaching-tick",
            "deliver": "local",
            "enabled": True,
            "state": "scheduled",
            "last_status": "error",
            "last_error": "weekly operations failed: canonical authority identity drift",
        }],
    }
    _ = cron.write_text(json.dumps(original), encoding="utf-8")
    dropin = tmp_path / "gateway.conf"
    _ = dropin.write_text("[Service]\n", encoding="utf-8")
    paths = R71bMaintenancePaths(
        profile, tmp_path / "successor/venv", cron, dropin
    )
    service = DisposableService()
    service.stop()
    files = R71bMaintenanceFiles(paths, service, artifacts.authority_bytes)

    # When
    files.arm()

    # Then
    assert files.hold_path.read_bytes() == artifacts.hold_bytes
    assert files.hold_path.stat().st_mode & 0o777 == 0o600
    assert files.credential_path.read_bytes() == artifacts.authority_bytes
    assert files.credential_path.stat().st_mode & 0o777 == 0o400
    assert (
        f"LoadCredential=nutricoach-topic59-maintenance-r71b.json:{files.credential_path}"
        in dropin.read_text(encoding="utf-8")
    )
    assert not files.audit_path.exists()

    # When
    files.rollback()

    # Then
    paused = json.loads(cron.read_text(encoding="utf-8"))["jobs"][0]
    assert paused["enabled"] is False
    assert paused["state"] == "paused"
    assert paused["last_error"] == original["jobs"][0]["last_error"]
    assert not files.hold_path.exists()
    assert not files.credential_path.exists()
    assert dropin.read_text(encoding="utf-8") == "[Service]\n"
