from __future__ import annotations

from datetime import date
import os
import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
TEST_RUNTIME = Path("/tmp") / f"financemanager-pytest-{os.getuid()}-{os.getpid()}"
TEST_DB = TEST_RUNTIME / "data" / "finance.sqlite3"
PRODUCTIVE_RUNTIME = Path("~/jarvis_runtime/finance-system").expanduser().resolve()

for variable in ("JARVIS_FINANCE_RUNTIME_DIR", "JARVIS_FINANCE_DB_PATH"):
    configured = os.environ.get(variable)
    if configured:
        resolved = Path(configured).expanduser().resolve()
        if resolved == PRODUCTIVE_RUNTIME or PRODUCTIVE_RUNTIME in resolved.parents:
            raise pytest.UsageError(f"{variable} points at the productive FinanceManager runtime")
        if Path("/tmp").resolve() not in (resolved, *resolved.parents):
            raise pytest.UsageError(f"{variable} must point below /tmp for tests")

os.environ["JARVIS_FINANCE_ENV"] = "test"
os.environ["JARVIS_FINANCE_RUNTIME_DIR"] = str(TEST_RUNTIME)
os.environ["JARVIS_FINANCE_DB_PATH"] = str(TEST_DB)
os.environ["JARVIS_FINANCE_WRITE_MODE"] = "test"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))


@pytest.fixture(scope="session", autouse=True)
def isolated_runtime_database() -> Path:
    """Make every default API dependency use a disposable schema below /tmp."""

    from jarvis_finance.storage.database import connect
    from jarvis_finance.storage.migrations import apply_migrations

    TEST_DB.parent.mkdir(parents=True, exist_ok=True)
    conn = connect(TEST_DB)
    try:
        apply_migrations(conn)
    finally:
        conn.close()
    return TEST_DB


@pytest.fixture
def budget_reference_date(monkeypatch: pytest.MonkeyPatch) -> date:
    """Keep budget tests anchored to their synthetic May 2026 ledger."""

    from jarvis_finance.services import budget_overview

    class ReferenceDate(date):
        @classmethod
        def today(cls) -> ReferenceDate:
            return cls(2026, 5, 31)

    monkeypatch.setattr(budget_overview, "date", ReferenceDate)
    return ReferenceDate.today()
