"""S4.7 / package 1: `modules.core.agent_schedule` is the only place outside the CRM calendar that knows the calendar file."""
import ast
import json
from pathlib import Path

import pytest

from modules.core import agent_schedule, storage_paths
from modules.core.json_store import JsonStoreCorrupt

ROOT = Path(__file__).resolve().parents[2]


@pytest.fixture()
def data(tmp_path, monkeypatch):
    monkeypatch.setenv(storage_paths.DATA_DIR_ENV_VAR, str(tmp_path))
    monkeypatch.setattr(storage_paths, 'REPO_ROOT', tmp_path)
    return tmp_path


def test_the_path_is_the_crm_calendar_file_and_the_crm_uses_the_same_definition(data):
    from InvestmentManager.routes import agent_panel_scheduler as crm
    expected = storage_paths.schedules_dir() / '101.json'
    assert agent_schedule.schedule_path(101) == expected and agent_schedule.schedule_path('101') == expected
    assert crm._schedule_path(101) == str(expected) and isinstance(crm._schedule_path(101), str)


def test_reading_a_missing_a_valid_and_a_damaged_calendar(data):
    assert agent_schedule.read_schedule_events(7) == []
    folder = storage_paths.schedules_dir()
    folder.mkdir(parents=True)
    (folder / '7.json').write_text(json.dumps([{'start': '2030-01-01'}, {'start': 'x', 'end': 'y'}]), encoding='utf-8')
    assert agent_schedule.read_schedule_events(7) == [{'start': '2030-01-01'}, {'start': 'x', 'end': 'y'}]        # stored events, uninterpreted
    (folder / '7.json').write_text('{oops', encoding='utf-8')
    with pytest.raises(JsonStoreCorrupt):
        agent_schedule.read_schedule_events(7)
    assert (folder / '7.json').read_text(encoding='utf-8') == '{oops'


def test_the_website_service_no_longer_opens_or_parses_the_calendar_itself():
    source = (ROOT / 'InvestmentWebsite/services/franchise_service.py').read_text(encoding='utf-8-sig')
    imported = set()
    for node in ast.walk(ast.parse(source)):
        if isinstance(node, ast.Import):
            imported.update(alias.name for alias in node.names)
        elif isinstance(node, ast.ImportFrom):
            imported.add(node.module)
    assert 'json' not in imported and 'modules.core.agent_schedule' in imported
    assert 'schedules_dir' not in source and 'read_text' not in source and 'json.loads' not in source
