"""Customer namespace races cannot affect profile-owned authority storage."""

from __future__ import annotations

import os
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime
from pathlib import Path
from threading import Barrier
from unittest.mock import patch

from checkin_cli.weekly_operations import AppendResult, CanonicalPin, CustomerKey, DayState, WeeklyOperationInput, customer_identity_digest
from checkin_cli.weekly_operations_authority import AuthorityId
from checkin_cli.weekly_operations_layout import customer_data_name
from checkin_cli.weekly_operations_store import WeeklyOperationsStore

from tests._weekly_operations_support import initialize_at

CUSTOMER = CustomerKey("client_001")
Mutation = Callable[[Path], tuple[Path, ...]]


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 _run_customer_race(tmp_path: Path, mutate: Mutation) -> tuple[type[AppendResult], int, tuple[bool, ...]]:
    authority_path = tmp_path / "profile/weekly-operations"
    authority_path.parent.mkdir(mode=0o700)
    authority = initialize_at(authority_path, AuthorityId("6" * 64))
    store = WeeklyOperationsStore.for_authority(authority, CUSTOMER)
    level_one, level_two = tmp_path / "customer-paths", tmp_path / "customer-paths/level-two"
    customer = level_two / "customer"
    level_one.mkdir(mode=0o700)
    level_two.mkdir(mode=0o700)
    customer.mkdir(mode=0o700)
    ready, mutated = Barrier(2), Barrier(2)
    first_write = iter((True,))
    real_write = os.write

    def gated_write(descriptor: int, payload: bytes) -> int:
        if next(first_write, False):
            _ = ready.wait(timeout=5)
            _ = mutated.wait(timeout=5)
        return real_write(descriptor, payload)

    with patch("os.write", side_effect=gated_write):
        with ThreadPoolExecutor(max_workers=1) as executor:
            result = executor.submit(store.append, _operation())
            _ = ready.wait(timeout=5)
            candidate_roots = mutate(customer)
            _ = mutated.wait(timeout=5)
            outcome = result.result(timeout=5)
    data = authority_path / customer_data_name(customer_identity_digest(CUSTOMER))
    customer_sidecars = tuple((root / "nutrition-plans/weekly-operations.jsonl").exists() for root in candidate_roots)
    return type(outcome), data.read_bytes().count(b"\n"), customer_sidecars


def test_final_customer_parent_rename_has_zero_storage_effect(tmp_path: Path) -> None:
    def mutate(customer: Path) -> tuple[Path, ...]:
        detached = customer.parent.with_name("level-two-detached")
        _ = customer.parent.replace(detached)
        customer.parent.mkdir(mode=0o700)
        customer.mkdir(mode=0o700)
        return detached / "customer", customer
    assert _run_customer_race(tmp_path, mutate) == (AppendResult, 1, (False, False))


def test_higher_customer_ancestor_rename_has_zero_storage_effect(tmp_path: Path) -> None:
    def mutate(customer: Path) -> tuple[Path, ...]:
        ancestor = customer.parents[1]
        detached = ancestor.with_name("customer-paths-detached")
        _ = ancestor.replace(detached)
        replacement = ancestor / "level-two/customer"
        replacement.mkdir(parents=True, mode=0o700)
        return detached / "level-two/customer", replacement
    assert _run_customer_race(tmp_path, mutate) == (AppendResult, 1, (False, False))


def test_customer_leaf_replacement_has_zero_storage_effect(tmp_path: Path) -> None:
    def mutate(customer: Path) -> tuple[Path, ...]:
        detached = customer.with_name("customer-detached")
        _ = customer.replace(detached)
        customer.mkdir(mode=0o700)
        return detached, customer
    assert _run_customer_race(tmp_path, mutate) == (AppendResult, 1, (False, False))


def test_customer_ancestor_rename_back_has_zero_storage_effect(tmp_path: Path) -> None:
    def mutate(customer: Path) -> tuple[Path, ...]:
        ancestor = customer.parents[1]
        detached = ancestor.with_name("customer-paths-detached")
        _ = ancestor.replace(detached)
        _ = detached.replace(ancestor)
        return customer, detached / "level-two/customer"
    assert _run_customer_race(tmp_path, mutate) == (AppendResult, 1, (False, False))
