"""Tests for the SCHEDULING LAYER (tick-driven, not a daemon).

Required coverage:
  1. next_run_at is computed deterministically for hourly / daily / weekly
  2. a tick fires ONLY the schedules that are due
  3. a tick is idempotent per due time — calling it twice does not double-fire
  4. toggling a schedule off stops it firing
  5. run-now fires regardless of next_run_at and records the run
  6. every run writes an audit row naming the schedule id, the action and outcome

Plus the HTTP surface: GET /schedules, GET/POST /api/schedules, toggle, run-now
and POST /api/scheduler/tick.
"""

from __future__ import annotations

import os
import tempfile
from datetime import datetime, timedelta, timezone

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-sched-test-")
os.environ["JARVIS_DB"] = os.path.join(_TMP, "test.db")
os.environ["JARVIS_MEMORY_DB"] = os.path.join(_TMP, "data", "jarvis.db")

from orchestrator import audit  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import scheduling  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402
from orchestrator.errors import ValidationError  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_db():
    db = os.environ["JARVIS_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(db + suffix)
        except FileNotFoundError:
            pass
    init_db()
    audit.init_db()
    memory.init_db()
    scheduling.init_db()
    REGISTRY.clear()
    register_default_components(REGISTRY)
    yield
    REGISTRY.clear()
    register_default_components(REGISTRY)


@pytest.fixture
def client():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        yield c


def _utc(text: str) -> datetime:
    return datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)


# --------------------------------------------------------------------------
# 1. next_run_at computation
# --------------------------------------------------------------------------

def test_next_run_hourly_is_the_next_occurrence_of_that_minute():
    after = "2024-06-10T14:20:00.000Z"  # 10:20 America/New_York (EDT, UTC-4)
    got = scheduling.next_run_at("hourly", at_minute=5, after=after)
    assert got == "2024-06-10T15:05:00.000Z"  # 11:05 EDT

    # exactly on the minute -> strictly after, so the NEXT hour
    on_the_minute = "2024-06-10T15:05:00.000Z"
    assert scheduling.next_run_at("hourly", at_minute=5, after=on_the_minute) == \
        "2024-06-10T16:05:00.000Z"


def test_next_run_hourly_is_deterministic():
    after = "2024-06-10T14:20:00.000Z"
    a = scheduling.next_run_at("hourly", at_minute=5, after=after)
    b = scheduling.next_run_at("hourly", at_minute=5, after=after)
    assert a == b


def test_next_run_daily_uses_wall_clock_in_new_york():
    # 2024-06-10T12:00Z = 08:00 EDT; 09:30 local is still ahead today
    assert scheduling.next_run_at("daily", at_hour=9, at_minute=30,
                                  after="2024-06-10T12:00:00.000Z") == \
        "2024-06-10T13:30:00.000Z"
    # 2024-06-10T14:00Z = 10:00 EDT; 09:30 local has passed -> tomorrow
    assert scheduling.next_run_at("daily", at_hour=9, at_minute=30,
                                  after="2024-06-10T14:00:00.000Z") == \
        "2024-06-11T13:30:00.000Z"


def test_next_run_daily_respects_dst_offset_change():
    # Winter (EST, UTC-5): 09:00 local == 14:00Z
    assert scheduling.next_run_at("daily", at_hour=9, at_minute=0,
                                  after="2024-01-10T00:00:00.000Z") == \
        "2024-01-10T14:00:00.000Z"
    # Summer (EDT, UTC-4): 09:00 local == 13:00Z
    assert scheduling.next_run_at("daily", at_hour=9, at_minute=0,
                                  after="2024-07-10T00:00:00.000Z") == \
        "2024-07-10T13:00:00.000Z"


def test_next_run_weekly_picks_the_next_listed_weekday():
    # 2024-06-10 is a Monday. Ask for Wed(2) at 09:00 local -> 2024-06-12 13:00Z
    got = scheduling.next_run_at("weekly", at_hour=9, at_minute=0, days_of_week="2",
                                 after="2024-06-10T12:00:00.000Z")
    assert got == "2024-06-12T13:00:00.000Z"
    assert _utc(got).astimezone(scheduling._tz()).weekday() == 2

    # Monday itself, but the time has passed -> next Monday
    got2 = scheduling.next_run_at("weekly", at_hour=9, at_minute=0, days_of_week="0",
                                  after="2024-06-10T14:00:00.000Z")
    assert got2 == "2024-06-17T13:00:00.000Z"


def test_next_run_weekly_requires_days():
    with pytest.raises(ValidationError):
        scheduling.next_run_at("weekly", at_hour=9, at_minute=0, days_of_week="")


def test_next_run_rejects_bad_cadence_and_bad_minute():
    with pytest.raises(ValidationError):
        scheduling.next_run_at("fortnightly", at_minute=0)
    with pytest.raises(ValidationError):
        scheduling.next_run_at("hourly", at_minute=99)


# --------------------------------------------------------------------------
# 2. tick fires only due schedules
# --------------------------------------------------------------------------

def _make_due(schedule_id: int, when: datetime) -> None:
    """Force a schedule's next_run_at into the past so it is due."""
    conn = connect()
    try:
        conn.execute("UPDATE schedules SET next_run_at = ? WHERE id = ?",
                     (scheduling.iso(when), schedule_id))
        conn.commit()
    finally:
        conn.close()


def test_tick_fires_only_due_schedules():
    due = scheduling.create_schedule("due one", "measure", cadence="daily",
                                     at_hour=9, at_minute=0)
    not_due = scheduling.create_schedule("later one", "measure", cadence="daily",
                                         at_hour=9, at_minute=0)
    now = datetime.now(timezone.utc)
    _make_due(due["id"], now - timedelta(minutes=5))
    # not_due keeps its future next_run_at

    result = scheduling.tick(now=now)

    fired_ids = [f["schedule_id"] for f in result["fired"]]
    assert fired_ids == [due["id"]]
    assert not_due["id"] not in fired_ids
    assert result["fired_count"] == 1
    assert result["background_daemon"] is False

    # the fired schedule advanced into the future and counted the run
    after = scheduling.get_schedule(due["id"])
    assert after["run_count"] == 1
    assert after["last_run_at"] is not None
    assert _utc(after["next_run_at"]) > now
    # the untouched one did not move
    assert scheduling.get_schedule(not_due["id"])["run_count"] == 0


def test_tick_with_nothing_due_fires_nothing():
    scheduling.create_schedule("future", "measure", cadence="daily", at_hour=9, at_minute=0)
    result = scheduling.tick()
    assert result["fired"] == []
    assert result["fired_count"] == 0
    assert result["enabled"] == 1


# --------------------------------------------------------------------------
# 3. idempotency per due time
# --------------------------------------------------------------------------

def test_tick_is_idempotent_for_the_same_due_time():
    sched = scheduling.create_schedule("once only", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    now = datetime.now(timezone.utc)
    _make_due(sched["id"], now - timedelta(minutes=1))

    first = scheduling.tick(now=now)
    second = scheduling.tick(now=now)  # same clock, called twice in a row

    assert first["fired_count"] == 1
    assert second["fired_count"] == 0, "the same due time must not fire twice"
    assert scheduling.get_schedule(sched["id"])["run_count"] == 1


def test_tick_idempotent_even_if_next_run_at_is_rewound():
    """Belt and braces: even if the row is forced back to the same due time, the
    last_run_at guard refuses the second fire."""
    sched = scheduling.create_schedule("guarded", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    now = datetime.now(timezone.utc)
    due_at = now - timedelta(minutes=1)
    _make_due(sched["id"], due_at)

    assert scheduling.tick(now=now)["fired_count"] == 1
    _make_due(sched["id"], due_at)  # rewind next_run_at to the same instant
    again = scheduling.tick(now=now)
    assert again["fired_count"] == 0
    assert scheduling.get_schedule(sched["id"])["run_count"] == 1


# --------------------------------------------------------------------------
# 4. toggle disables firing
# --------------------------------------------------------------------------

def test_toggle_disables_firing():
    sched = scheduling.create_schedule("toggled", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    now = datetime.now(timezone.utc)
    _make_due(sched["id"], now - timedelta(minutes=1))

    off = scheduling.toggle_schedule(sched["id"])
    assert off["enabled"] is False

    result = scheduling.tick(now=now)
    assert result["fired_count"] == 0
    assert scheduling.get_schedule(sched["id"])["run_count"] == 0

    on = scheduling.toggle_schedule(sched["id"])
    assert on["enabled"] is True
    # re-enabling recomputed the next occurrence from now, so it is not due
    assert _utc(on["next_run_at"]) > now


def test_toggle_unknown_schedule_raises():
    with pytest.raises(ValidationError):
        scheduling.toggle_schedule(999999)


# --------------------------------------------------------------------------
# 5. run-now fires regardless of due time
# --------------------------------------------------------------------------

def test_run_now_fires_regardless_of_due_time():
    sched = scheduling.create_schedule("manual", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    assert _utc(sched["next_run_at"]) > datetime.now(timezone.utc)  # not due

    result = scheduling.run_now(sched["id"])

    assert result["schedule_id"] == sched["id"]
    assert result["trigger"] == "manual"
    assert result["outcome"] in ("ok", "degraded")
    after = scheduling.get_schedule(sched["id"])
    assert after["run_count"] == 1
    assert after["last_run_at"] is not None
    # a manual run resets the cadence clock, so the next tick cannot repeat it
    assert scheduling.tick()["fired_count"] == 0


def test_run_now_unknown_schedule_raises():
    with pytest.raises(ValidationError):
        scheduling.run_now(424242)


# --------------------------------------------------------------------------
# 6. audit rows
# --------------------------------------------------------------------------

def test_tick_writes_an_audit_row_per_run():
    sched = scheduling.create_schedule("audited", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    now = datetime.now(timezone.utc)
    _make_due(sched["id"], now - timedelta(minutes=1))
    before = audit.verify()["length"]

    result = scheduling.tick(now=now)
    assert result["fired_count"] == 1

    rows = audit.recent(limit=50, actor=scheduling.COMPONENT_NAME, action="schedule.run")
    assert rows, "a run must be recorded in the audit ledger"
    run_row = rows[0]
    assert run_row["subject_id"] == str(sched["id"])
    assert run_row["payload"]["schedule_id"] == sched["id"]
    assert run_row["payload"]["target_kind"] == "measure"
    assert run_row["payload"]["outcome"] in ("ok", "degraded")
    assert run_row["payload"]["trigger"] == "tick"
    assert run_row["payload"]["due_at"]

    # the tick itself is audited too, and the chain still verifies
    tick_rows = audit.recent(limit=50, actor=scheduling.COMPONENT_NAME, action="schedule.tick")
    assert tick_rows and tick_rows[0]["payload"]["fired"] == 1
    state = audit.verify()
    assert state["ok"] is True
    assert state["length"] > before


def test_run_now_writes_an_audit_row():
    sched = scheduling.create_schedule("manual audit", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    result = scheduling.run_now(sched["id"])
    assert result["audit_seq"]
    rows = audit.recent(limit=20, actor=scheduling.COMPONENT_NAME, action="schedule.run")
    assert rows[0]["payload"]["trigger"] == "manual"
    assert rows[0]["subject_id"] == str(sched["id"])


# --------------------------------------------------------------------------
# seed
# --------------------------------------------------------------------------

def test_seed_creates_three_enabled_labelled_schedules():
    created = scheduling.seed_if_empty()
    assert created == 3
    rows = scheduling.list_schedules()
    assert len(rows) == 3
    assert all(r["enabled"] for r in rows)
    assert all(r["seeded"] for r in rows)
    assert all(r["name"].startswith("Seeded:") for r in rows)
    kinds = {r["target_kind"] for r in rows}
    assert kinds == {"ingest", "opportunities", "verify"}
    # idempotent: a second call adds nothing
    assert scheduling.seed_if_empty() == 0


# --------------------------------------------------------------------------
# HTTP surface
# --------------------------------------------------------------------------

def test_schedules_page_renders_seeded_rows(client):
    scheduling.seed_if_empty()
    resp = client.get("/schedules")
    assert resp.status_code == 200
    body = resp.get_data(as_text=True)
    assert "Seeded: hourly ingest" in body
    assert "Seeded: daily opportunities" in body
    assert "Seeded: daily verification pass" in body
    assert "Tick now" in body
    # The page must be honest about what the scheduler IS and IS NOT. It is now a
    # real in-process background thread, and it is still not an OS supervisor.
    assert "in-process scheduler" in body.lower()
    assert "not an os-level supervisor" in body.lower()
    assert "no systemd unit" in body.lower()
    assert "run now" in body.lower()


def test_api_schedules_lists_json(client):
    scheduling.seed_if_empty()
    resp = client.get("/api/schedules")
    assert resp.status_code == 200
    body = resp.get_json()
    assert body["count"] == 3
    assert body["enabled"] == 3
    assert body["tick_driven"] is True
    assert body["background_daemon"] is False
    assert body["timezone"] == "America/New_York"
    assert len(body["schedules"]) == 3


def test_api_create_toggle_run_now_and_tick(client):
    created = client.post("/api/schedules", json={
        "name": "api created", "target_kind": "measure",
        "cadence": "weekly", "at_hour": 8, "at_minute": 30, "days_of_week": "1,3",
    })
    assert created.status_code == 201
    sched = created.get_json()["schedule"]
    assert sched["name"] == "api created"
    assert sched["cadence"] == "weekly"
    assert sched["days"] == [1, 3]
    assert sched["enabled"] is True

    toggled = client.post(f"/api/schedules/{sched['id']}/toggle")
    assert toggled.status_code == 200
    assert toggled.get_json()["enabled"] is False

    ran = client.post(f"/api/schedules/{sched['id']}/run-now")
    assert ran.status_code == 200
    assert ran.get_json()["trigger"] == "manual"

    tick = client.post("/api/scheduler/tick")
    assert tick.status_code == 200
    payload = tick.get_json()
    assert "fired" in payload and "message" in payload
    assert payload["background_daemon"] is False


def test_api_create_rejects_bad_target_kind(client):
    resp = client.post("/api/schedules", json={"name": "bad", "target_kind": "nope"})
    assert resp.status_code == 400
    assert resp.get_json()["error"] == "bad_request"  # ValidationError.code


def test_api_tick_reports_what_fired(client):
    sched = scheduling.create_schedule("due now", "measure", cadence="daily",
                                       at_hour=9, at_minute=0)
    _make_due(sched["id"], datetime.now(timezone.utc) - timedelta(minutes=2))
    resp = client.post("/api/scheduler/tick")
    assert resp.status_code == 200
    body = resp.get_json()
    assert body["fired_count"] == 1
    assert body["fired"][0]["schedule_id"] == sched["id"]
    assert body["fired"][0]["outcome"] in ("ok", "degraded")
    assert body["fired"][0]["summary"]


def test_scheduling_layer_is_registered_as_a_tool():
    component = REGISTRY.get(scheduling.COMPONENT_NAME)
    assert component is not None
    assert component.handles_state is None  # a tool never transitions a job
