"""S4.7 / package 1 (approved exception): a damaged agent calendar FAILS CLOSED in the public franchise booking.

Before: an unreadable calendar was treated as empty and every working slot was offered. Now: no slot is offered, no booking is accepted,
the file is never rewritten, nothing about the cause reaches the visitor, and the cause is logged with a request id.
Missing or valid calendars behave exactly as before (see test_s47p1_franchise_calendar_characterization.py).
"""
import json
import os

import pytest

from modules.core import agent_schedule
from tests.investmentmanager.test_s47p1_franchise_calendar_characterization import (  # noqa: F401
    ALL, FakeDate, FakeDateTime, availability, book, by_day, world, write_schedule)

DAMAGED = ['{not json', '', '{"a": 1}', '"text"', '5', 'null', '{broken']


@pytest.mark.parametrize('content', DAMAGED)
def test_a_damaged_calendar_offers_no_time_and_is_left_untouched(app, world, content, caplog):
    path = write_schedule(world, content)
    before = path.read_bytes()
    with caplog.at_level('ERROR'):
        payload = availability(app)
    assert payload['days'] == []                                              # not "every slot free"
    assert set(payload) == {'agent_id', 'slot_minutes', 'days', 'source_options'} and payload['agent_id'] == 101      # same shape, no error field
    assert path.read_bytes() == before                                        # never rewritten
    assert 'JsonStore' not in json.dumps(payload) and 'broken' not in json.dumps(payload)
    records = [r for r in caplog.records if 'franchise.calendar_unreadable' in r.getMessage()]
    assert records and 'request_id=' in records[0].getMessage()               # the operator can see why


@pytest.mark.parametrize('content', DAMAGED)
def test_a_damaged_calendar_refuses_every_booking_with_the_ordinary_message(app, world, content):
    write_schedule(world, content)
    for start in ('2030-01-07T09:00', '2030-01-08T10:00'):
        body, status = book(app, start)
        assert (body, status) == ({'success': False, 'error': 'Wybrany termin nie jest już dostępny.'}, 409)
    assert world['created'] == []                                              # no client, no meeting


def test_the_damaged_file_keeps_only_the_diagnostic_copy_of_json_store(app, world):
    path = write_schedule(world, '{not json')
    availability(app)
    siblings = sorted(p.name for p in world['dir'].iterdir())
    assert siblings[0] == '101.json' and len(siblings) == 2 and siblings[1].startswith('101.json.corrupt-')
    assert path.read_text(encoding='utf-8') == '{not json'
    availability(app)
    assert len(list(world['dir'].iterdir())) == 2                              # the copy is idempotent


def test_slots_come_back_as_soon_as_the_calendar_is_valid_again(app, world):
    write_schedule(world, '{not json')
    assert availability(app)['days'] == []
    write_schedule(world, [{'start': '2030-01-08T10:00', 'end': '2030-01-08T11:00'}])
    days = by_day(availability(app))
    assert days['2030-01-08'] == [label for label in ALL if label != '10:00'] and days['2030-01-07'] == ALL
    assert book(app, '2030-01-07T09:00')[1] == 200


def test_an_unreadable_file_is_treated_like_a_damaged_one(app, world, monkeypatch):
    import InvestmentWebsite.services.franchise_service as fs

    def denied(agent_id):
        raise PermissionError('denied /home/secret/path')
    monkeypatch.setattr(fs, 'read_schedule_events', denied)
    payload = availability(app)
    assert payload['days'] == [] and 'secret' not in json.dumps(payload)
    assert book(app, '2030-01-07T09:00')[1] == 409


@pytest.mark.skipif(os.name != 'posix', reason='symbolic links are reliably available on POSIX')
def test_a_symlinked_calendar_is_refused_and_closes_the_booking(app, world, tmp_path):
    world['dir'].mkdir(parents=True, exist_ok=True)
    target = tmp_path / 'elsewhere.json'
    target.write_text('[]', encoding='utf-8')
    (world['dir'] / '101.json').symlink_to(target)
    assert availability(app)['days'] == [] and book(app, '2030-01-07T09:00')[1] == 409


def test_a_missing_calendar_is_still_a_fully_free_calendar(app, world):
    assert not agent_schedule.schedule_path(101).exists()
    assert all(labels == ALL for labels in by_day(availability(app)).values())
