#!/usr/bin/env python3
"""Direct, content-free verifier for the one Task23 Codex authorization."""

from __future__ import annotations

import argparse
import hashlib
import json
import subprocess
import sys
from pathlib import Path
from typing import cast

PROFILE_ROOT = Path("/home/cube/.hermes/profiles/dualcoachtest")
SOURCE_ROOT = Path("/home/cube/projects/richard/hermes-agent")
OWNER = ("9000000001", "9000000001", "0")
PARENT = "e2f07f9a41431ff1"
PARENT_DIGEST = "429a45f63878ae3fa568077ea057a6195486c8d40e6b137df8c9cc5da671a9c1"
PREDECESSOR = "664046dbca210afc"
PREDECESSOR_DIGEST = "9bc0920c5be80a312ab04f3cbb4f75a4d69cbee967ed9bddd402959ea7347454"
CHILD = "01e3b5d1739a5c49"


def _canonical(value: object) -> bytes:
    return json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
        allow_nan=False,
    ).encode("utf-8")


def _service_active() -> bool:
    return subprocess.run(
        ["systemctl", "--user", "is-active", "--quiet", "hermes-gateway-dualcoachtest.service"],
        check=False,
        capture_output=True,
    ).returncode == 0


def _store():
    sys.path.insert(0, str(SOURCE_ROOT))
    from gateway.platforms.task23_codex_compatibility_repair import (
        Task23CodexCompatibilityRepairStore,
    )

    return Task23CodexCompatibilityRepairStore(PROFILE_ROOT, source_root=SOURCE_ROOT)


def _journal(store: object) -> dict[str, object]:
    path = cast(Path, getattr(store, "journal_path"))
    return cast(dict[str, object], json.loads(path.read_text(encoding="utf-8")))


def _pre_consume() -> dict[str, object]:
    store = _store()
    journal = _journal(store)
    seal = store._seal_from_dict(journal["seal"])
    store._validate_journal(journal, seal=seal)
    current = store.preflight()
    current_values = current.as_dict()
    prior_values = seal.as_dict()
    assert all(
        current_values[key] == prior_values[key]
        for key in current_values
        if key not in {"source_repair_sha256", "seal_digest"}
    )
    assert journal["state"] == "owner_authorized"
    assert journal["owner"] == list(OWNER)
    assert journal["publication"] == {
        "chat_id": OWNER[1], "topic_id": OWNER[2], "message_id": "144"
    }
    assert journal["authorization"] == {
        "actor_user_id": OWNER[0],
        "chat_id": OWNER[1],
        "topic_id": OWNER[2],
        "message_id": "144",
        "update_id": 629525075,
    }
    assert journal["prospective_child"]["token"] == CHILD
    callback_data_sha256 = hashlib.sha256(
        journal["callback_data"].encode("utf-8")
    ).hexdigest()
    resolved = store.resolve_authorization(
        expected_card_id=journal["card_id"],
        expected_callback_update_id=629525075,
        expected_callback_message_id="144",
        expected_callback_data_sha256=callback_data_sha256,
        expected_seal_digest=journal["seal_digest"],
        expected_child_token=CHILD,
    )
    assert resolved.owner.key == OWNER
    assert resolved.callback_update_id == 629525075
    assert resolved.callback_message_id == "144"
    assert resolved.card_id == journal["card_id"]
    callback_projection = json.loads(
        (
            PROFILE_ROOT
            / "data"
            / "onboarding"
            / "telegram-publication-outbox-v1"
            / "owner-callbacks.json"
        ).read_text(encoding="utf-8")
    )
    callback_records = callback_projection["records"]
    assert all(
        not isinstance(record, dict) or record.get("update_id") != 629525075
        for record in callback_records
    )
    ingress_bytes = (
        PROFILE_ROOT / "data" / "telegram-ingress-receipts-v1-d0aacf0f4bdbb7c0.json"
    ).read_bytes()
    assert b"629525075" not in ingress_bytes
    from gateway.platforms.nutrition_coaching import (
        NutritionCoachingCoordinator,
        load_committed_customer_registry,
    )

    registry, registry_path = load_committed_customer_registry(PROFILE_ROOT)
    coordinator = NutritionCoachingCoordinator(
        PROFILE_ROOT, registry, registry_path=registry_path
    )
    assert coordinator._ensure_live_registry()
    assert coordinator.owner.key == resolved.owner.key
    assert journal["generation_child_append_count"] == 0
    assert journal["provider_generation_called"] is False
    assert journal["customer_delivery_count"] == 0
    assert "consume_intent" not in journal
    assert "reseal" not in journal
    assert hashlib.sha256(
        _canonical({key: value for key, value in journal.items() if key != "journal_digest"})
    ).hexdigest() == journal["journal_digest"]
    generations = json.loads(
        (PROFILE_ROOT / "data" / "owner-actions" / "draft-generations.json").read_text(
            encoding="utf-8"
        )
    )
    parent = generations[PARENT][-1]
    predecessor = generations[PREDECESSOR][-1]
    assert parent["generation"] == 3
    assert parent["record_digest"] == PARENT_DIGEST
    assert parent["state"] == "generation_failed"
    assert predecessor["record_digest"] == PREDECESSOR_DIGEST
    descendants = [
        token
        for token, history in generations.items()
        if token != PARENT
        and isinstance(history, list)
        and history
        and history[0].get("lineage_predecessor_digest") == PARENT_DIGEST
    ]
    assert not descendants
    return {
        "schema": "task23-codex-live-direct-verifier-v3",
        "phase": "pre_consume",
        "verifier": "passed",
        "authorization": {
            "message_id": "144",
            "update_id": 629525075,
            "owner_route": {"user_id": OWNER[0], "chat_id": OWNER[1], "topic_id": OWNER[2]},
            "journal_digest": journal["journal_digest"],
            "prior_seal_digest": seal.seal_digest,
            "current_candidate_seal_digest": current.seal_digest,
            "callback_data_sha256": callback_data_sha256,
        },
        "authority_projection": {
            "durable_task23_journal_match_count": 1,
            "generic_owner_callback_update_629525075_present": False,
            "telegram_ingress_update_629525075_present": False,
            "live_registry_owner_matches_durable_callback": True,
        },
        "lineage": {
            "predecessor_token": PREDECESSOR,
            "predecessor_record_digest": PREDECESSOR_DIGEST,
            "parent_token": PARENT,
            "parent_generation": 3,
            "parent_record_digest": PARENT_DIGEST,
            "prospective_child_token": CHILD,
            "descendant_count": 0,
        },
        "invariants": {
            "provider_generation_called": False,
            "customer_delivery_count": 0,
            "service_active": _service_active(),
        },
    }


def _post_generation() -> dict[str, object]:
    store = _store()
    journal = store.verify_consumed_authorization()
    assert journal["prospective_child"]["token"] == CHILD
    assert journal["generation_child_append_count"] == 1
    assert journal["provider_generation_called"] is False
    assert journal["customer_delivery_count"] == 0
    assert journal["reseal"]["count"] == 1
    assert journal["authorization"]["update_id"] == 629525075
    package_root = PROFILE_ROOT / "workspace" / "checkin_cli"
    sys.path.insert(0, str(package_root))
    from gateway.platforms.nutrition_coaching import (
        DraftGenerationState,
        IncomingAddress,
        NutritionCoachingCoordinator,
        load_committed_customer_registry,
    )

    registry, registry_path = load_committed_customer_registry(PROFILE_ROOT)
    coordinator = NutritionCoachingCoordinator(PROFILE_ROOT, registry, registry_path=registry_path)
    history = coordinator.draft_generation_history(CHILD)
    assert history and history[0].record_digest == journal["consume_intent"]["initial_record"]["record_digest"]
    assert history[0].lineage_parent_token == PARENT
    assert history[0].lineage_predecessor_digest == PARENT_DIGEST
    current = history[-1]
    assert current.state in {
        DraftGenerationState.DRAFT_CREATED,
        DraftGenerationState.GENERATION_FAILED,
    }
    descendants = [
        token
        for token, candidate in coordinator._read_draft_generations().items()
        if token != PARENT
        and candidate
        and candidate[0].lineage_predecessor_digest == PARENT_DIGEST
    ]
    assert descendants == [CHILD]
    drafts = coordinator._read_drafts()
    deliveries = coordinator._read_deliveries()
    cards = coordinator._read_draft_generation_cards()
    child_cards = [
        value for value in cards.values() if value.get("token") == CHILD
    ]
    if current.state is DraftGenerationState.DRAFT_CREATED:
        assert CHILD in drafts
        assert current.generation_provider_receipt is not None
        assert len(child_cards) == 1 and child_cards[0]["state"] == "published"
    else:
        assert CHILD not in drafts
        assert current.error is not None
    assert not deliveries
    return {
        "schema": "task23-codex-live-direct-verifier-v2",
        "phase": "post_generation",
        "verifier": "passed",
        "authorization": {
            "journal_state": journal["state"],
            "journal_digest": journal["journal_digest"],
            "reseal": journal["reseal"],
        },
        "child": {
            "token": CHILD,
            "history_states": [record.state.value for record in history],
            "state": current.state.value,
            "generation": current.generation,
            "record_digest": current.record_digest,
            "provider_receipt_present": current.generation_provider_receipt is not None,
            "error_code": current.error.code if current.error is not None else None,
            "provider_failure_audit_count": len(current.error.provider_failure_audits) if current.error is not None else 0,
        },
        "invariants": {
            "descendant_count": 1,
            "owner_review_card_count": len(child_cards),
            "customer_delivery_count": 0,
            "service_active": _service_active(),
        },
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--phase", choices=("pre-consume", "post-generation"), required=True)
    args = parser.parse_args()
    result = _pre_consume() if args.phase == "pre-consume" else _post_generation()
    print(json.dumps(result, ensure_ascii=False, sort_keys=True, separators=(",", ":")))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
