"""Dedicated pre-existing authority-root capability tests."""

from __future__ import annotations

from datetime import date, datetime
from pathlib import Path
from unittest import TestCase
from unittest.mock import patch

import checkin_cli.weekly_operations_parent as parent_module
from checkin_cli.weekly_operations import CanonicalPin, CustomerKey, DayState, WeeklyOperationInput, WeeklyOperationsAuthorityCompromise
from checkin_cli.weekly_operations_authority import AuthorityId, open_authority_root
from checkin_cli.weekly_operations_parent import acquire_parent_authority, reacquire_parent_authority
from checkin_cli.weekly_operations_store import WeeklyOperationsStore
from tests._weekly_operations_support import initialize_for_parent

ASSERTIONS = TestCase()
CUSTOMER = CustomerKey("client_001")


def _operation() -> WeeklyOperationInput:
    return WeeklyOperationInput.for_customer(CUSTOMER, date(2026, 8, 17), DayState.SUBMITTED, CanonicalPin(1, "a" * 64), datetime.fromisoformat("2026-08-17T20:00:00+09:00"))


def test_typed_parent_capability_api_exists() -> None:
    assert hasattr(parent_module, "WeeklyOperationsParentAuthority")
    assert hasattr(parent_module, "acquire_parent_authority")
    assert hasattr(parent_module, "reacquire_parent_authority")


def test_existing_empty_directory_is_the_initialized_root(tmp_path: Path) -> None:
    root = tmp_path / "authority"
    root.mkdir(mode=0o700)
    before = root.stat().st_dev, root.stat().st_ino
    authority = initialize_for_parent(acquire_parent_authority(root), AuthorityId("d" * 64))
    assert (root.stat().st_dev, root.stat().st_ino) == before
    assert (authority.binding.root_device, authority.binding.root_inode) == before
    authority.close()


def test_product_initialization_never_mkdirs_authority_root(tmp_path: Path) -> None:
    root = tmp_path / "authority"
    root.mkdir(mode=0o700)
    with patch("os.mkdir", side_effect=AssertionError("product mkdir is forbidden")):
        authority = initialize_for_parent(acquire_parent_authority(root), AuthorityId("e" * 64))
    authority.close()


def test_root_path_rename_before_initialization_cannot_redirect_publication(tmp_path: Path) -> None:
    root = tmp_path / "authority"
    root.mkdir(mode=0o700)
    parent = acquire_parent_authority(root)
    detached = tmp_path / "authority-detached"
    _ = root.replace(detached)
    root.mkdir(mode=0o700)
    authority = initialize_for_parent(parent, AuthorityId("f" * 64))
    assert (detached / "authority-v1.json").is_file() and tuple(root.iterdir()) == ()
    authority.close()


def test_parent_binding_reacquires_only_same_root_inode(tmp_path: Path) -> None:
    root = tmp_path / "authority"
    root.mkdir(mode=0o700)
    parent = acquire_parent_authority(root)
    authority = initialize_for_parent(parent, AuthorityId("0" * 64))
    reacquired = reacquire_parent_authority(root, parent.binding)
    reopened = open_authority_root(reacquired, authority.binding)
    assert WeeklyOperationsStore.for_authority(reopened, CUSTOMER).read() == ()
    reopened.close()


def test_recreated_bootstrap_path_cannot_reacquire_bound_root(tmp_path: Path) -> None:
    root = tmp_path / "authority"
    root.mkdir(mode=0o700)
    parent = acquire_parent_authority(root)
    detached = tmp_path / "authority-detached"
    _ = root.replace(detached)
    root.mkdir(mode=0o700)
    with ASSERTIONS.assertRaises(WeeklyOperationsAuthorityCompromise):
        _ = reacquire_parent_authority(root, parent.binding)
    assert tuple(root.iterdir()) == ()


def test_uncooperative_root_path_replacement_cannot_redirect_store_write(tmp_path: Path) -> None:
    root = tmp_path / "authority"
    root.mkdir(mode=0o700)
    authority = initialize_for_parent(acquire_parent_authority(root), AuthorityId("1" * 64))
    detached = tmp_path / "authority-detached"
    _ = root.replace(detached)
    root.mkdir(mode=0o700)
    result = WeeklyOperationsStore.for_authority(authority, CUSTOMER).append(_operation())
    assert result.appended and tuple(root.iterdir()) == ()
    assert len(tuple(detached.glob("*.day-status-v1.jsonl"))) == 1
