from __future__ import annotations

from oasyce.services.inbox import ConfirmationInbox
from oasyce.services.mandate_service import (
    MANDATE_PROFILE_BALANCED,
    MANDATE_PROFILE_CASHFLOW,
    MANDATE_PROFILE_DISTRIBUTION,
    MANDATE_REVIEW_ALL_CANDIDATES,
    apply_mandate_to_runtime,
    load_mandate,
    requires_manual_review_for_candidate,
    resolve_mandate_runtime_defaults,
    set_mandate_profile,
)
from oasyce.services.scanner import AssetScanner
from oasyce.services.scheduler import AgentScheduler, SchedulerConfig


def test_set_mandate_profile_persists_profile(tmp_path):
    mandate = set_mandate_profile(MANDATE_PROFILE_DISTRIBUTION, data_dir=str(tmp_path))

    reloaded = load_mandate(str(tmp_path))

    assert mandate.profile == MANDATE_PROFILE_DISTRIBUTION
    assert reloaded.profile == MANDATE_PROFILE_DISTRIBUTION
    assert reloaded.trade_mode == "disabled"


def test_resolve_runtime_defaults_uses_current_mandate(tmp_path):
    set_mandate_profile(MANDATE_PROFILE_CASHFLOW, data_dir=str(tmp_path))

    resolved = resolve_mandate_runtime_defaults(data_dir=str(tmp_path))

    assert resolved["auto_trade"] is True
    assert resolved["trade_tags"] == ["data", "model"]
    assert resolved["trade_max_spend"] == 20.0
    assert resolved["trust_level"] == 1


def test_apply_mandate_to_runtime_syncs_scheduler_and_inbox(tmp_path):
    set_mandate_profile(MANDATE_PROFILE_CASHFLOW, data_dir=str(tmp_path))
    inbox = ConfirmationInbox(data_dir=str(tmp_path))
    scheduler = AgentScheduler(
        SchedulerConfig(enabled=False, scan_paths=["/tmp/docs"], auto_register=True),
        scanner=AssetScanner(),
        inbox=inbox,
        data_dir=str(tmp_path),
    )

    payload = apply_mandate_to_runtime(
        data_dir=str(tmp_path),
        scheduler=scheduler,
        inbox=inbox,
    )
    config = scheduler.get_config()

    assert payload["changed"] is True
    assert config.auto_trade is True
    assert config.trade_tags == ["data", "model"]
    assert config.trade_max_spend == 20.0
    assert inbox.get_trust_level() == 1
    assert inbox.get_auto_threshold() == 10.0


def test_requires_manual_review_for_candidate_reads_mandate(tmp_path):
    set_mandate_profile(MANDATE_PROFILE_BALANCED, data_dir=str(tmp_path))
    assert requires_manual_review_for_candidate(data_dir=str(tmp_path)) is None

    mandate = load_mandate(str(tmp_path))
    updated = mandate.__class__(
        **{**mandate.to_dict(), "review_mode": MANDATE_REVIEW_ALL_CANDIDATES}
    )
    from oasyce.services.mandate_service import save_mandate

    save_mandate(updated, data_dir=str(tmp_path))

    assert requires_manual_review_for_candidate(data_dir=str(tmp_path)) == "mandate_requires_review"
