"""S4.7 / package 1: characterization of the public franchise availability and booking against the CRM agent calendar.

Observed through `InvestmentWebsite.services.franchise_service` only, with a frozen clock (Monday 2030-01-07 08:00), a throw-away DATA_DIR
and faked CRM client store. Written and passing on the OLD code; the valid-file / missing-file / all-day / meeting cases must pass unchanged
after the calendar read moves behind `modules.core.agent_schedule`. The behaviour for a DAMAGED calendar (old: treated as empty, every slot offered) is the one change
package 1 makes on purpose; it is covered by `test_franchise_calendar_failclosed.py`.
"""
from datetime import date as real_date, datetime as real_datetime
import json

import pytest

import InvestmentWebsite.services.franchise_service as fs
from modules.core import storage_paths


class FakeDateTime(real_datetime):
    @classmethod
    def now(cls, tz=None):
        return cls(2030, 1, 7, 8, 0)


class FakeDate(real_date):
    @classmethod
    def today(cls):
        return cls(2030, 1, 7)


@pytest.fixture()
def world(app, tmp_path, monkeypatch):
    monkeypatch.setenv(storage_paths.DATA_DIR_ENV_VAR, str(tmp_path))
    monkeypatch.setattr(storage_paths, 'REPO_ROOT', tmp_path)
    monkeypatch.setattr(fs, 'datetime', FakeDateTime)
    monkeypatch.setattr(fs, 'date', FakeDate)
    state = {'meetings': [], 'created': []}
    monkeypatch.setattr(fs, 'list_agent_calendar_meetings', lambda agent_id: list(state['meetings']))
    monkeypatch.setattr(fs, '_send_franchise_meeting_email', lambda **kwargs: None)

    def create_client(payload, **kwargs):
        state['created'].append(('client', payload['first_name'], kwargs['owner_agent_id']))
        return {'id': 41, 'first_name': payload['first_name'], 'last_name': payload['last_name']}, []

    def create_client_meeting(client_id, payload, **kwargs):
        state['created'].append(('meeting', client_id, payload['start_at']))
        return {'id': 77, 'start_at': payload['start_at']}
    monkeypatch.setattr(fs, 'create_client', create_client)
    monkeypatch.setattr(fs, 'create_client_meeting', create_client_meeting)
    state['dir'] = storage_paths.schedules_dir()
    return state


def write_schedule(world, content, agent_id=101):
    world['dir'].mkdir(parents=True, exist_ok=True)
    path = world['dir'] / f'{agent_id}.json'
    path.write_text(content if isinstance(content, str) else json.dumps(content), encoding='utf-8')
    return path


def availability(app):
    with app.app_context():
        return fs.get_public_franchise_availability()


def by_day(payload):
    return {day['date']: [slot['label'] for slot in day['slots']] for day in payload['days']}


ALL = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00']


def test_missing_calendar_gives_every_working_slot_of_the_window(app, world):
    payload = availability(app)
    assert set(payload) == {'agent_id', 'slot_minutes', 'days', 'source_options'}
    assert payload['agent_id'] == 101 and payload['slot_minutes'] == 60
    assert payload['source_options'] == [{'value': 'franczyza', 'label': 'Formularz franczyza'}, {'value': 'lexpress', 'label': 'Lexpress Franchise'}]
    days = by_day(payload)
    assert len(days) == 15 and list(days)[0] == '2030-01-07' and list(days)[-1] == '2030-01-25'     # 21 days, weekends skipped
    assert all(labels == ALL for labels in days.values())
    first = payload['days'][0]
    assert first['label'] == '07.01.2030' and first['weekday_label'] == 'Poniedziałek'
    assert first['slots'][0] == {'start_at': '2030-01-07T09:00', 'end_at': '2030-01-07T10:00', 'label': '09:00'}


def test_an_empty_calendar_list_changes_nothing(app, world):
    write_schedule(world, [])
    assert all(labels == ALL for labels in by_day(availability(app)).values())


def test_a_timed_event_blocks_every_overlapping_slot(app, world):
    write_schedule(world, [{'start': '2030-01-08T10:00', 'end': '2030-01-08T11:30'}])
    days = by_day(availability(app))
    assert days['2030-01-08'] == ['09:00', '12:00', '13:00', '14:00', '15:00', '16:00']       # 10:00 and 11:00 (ends 12:00 > 11:30) blocked
    assert days['2030-01-07'] == ALL and days['2030-01-09'] == ALL


def test_an_event_without_end_blocks_one_slot_length(app, world):
    write_schedule(world, [{'start': '2030-01-10T14:00'}])
    assert by_day(availability(app))['2030-01-10'] == [label for label in ALL if label != '14:00']


def test_an_all_day_event_without_end_blocks_the_whole_day(app, world):
    write_schedule(world, [{'start': '2030-01-09'}])
    days = by_day(availability(app))
    assert '2030-01-09' not in days and len(days) == 14


def test_events_that_cannot_be_interpreted_are_ignored(app, world):
    write_schedule(world, [{'end': '2030-01-08T10:00'}, {'start': ''}, {'start': 'garbage'},
                           {'start': '2030-01-11T10:00', 'end': '2030-01-11T09:00'}, {'start': '2030-01-11T10:00', 'end': '2030-01-11T10:00'}])
    assert all(labels == ALL for labels in by_day(availability(app)).values())


def test_crm_meetings_block_slots_except_cancelled_ones_and_default_to_one_slot(app, world):
    world['meetings'] = [
        {'start_at': '2030-01-14T09:00', 'end_at': '2030-01-14T10:00', 'meeting_status': 'planned'},
        {'start_at': '2030-01-14T11:00', 'meeting_status': ' CANCELLED '},
        {'start_at': '2030-01-14T13:00'},
        {'start_at': ''},
    ]
    assert by_day(availability(app))['2030-01-14'] == [label for label in ALL if label not in ('09:00', '13:00')]


def test_calendar_events_and_meetings_are_combined(app, world):
    write_schedule(world, [{'start': '2030-01-15T09:00', 'end': '2030-01-15T10:00'}])
    world['meetings'] = [{'start_at': '2030-01-15T16:00', 'end_at': '2030-01-15T17:00'}]
    assert by_day(availability(app))['2030-01-15'] == ['10:00', '11:00', '12:00', '13:00', '14:00', '15:00']


def test_another_agents_calendar_is_not_used(app, world):
    write_schedule(world, [{'start': '2030-01-08'}], agent_id=102)
    assert '2030-01-08' in by_day(availability(app))


# ---------------------------------------------------------------------------------------------------------------------- booking
def book(app, start_at, **overrides):
    payload = {'first_name': 'Jan', 'last_name': 'Kowalski', 'phone': '600100200', 'email': 'jan@example.invalid', 'city': 'Gdansk',
               'start_at': start_at, **overrides}
    with app.app_context():
        return fs.book_public_franchise_meeting(payload)


def test_booking_a_free_slot_creates_the_client_and_the_meeting(app, world):
    body, status = book(app, '2030-01-07T09:00')
    assert status == 200 and body['success'] is True and body['client_id'] == 41 and body['meeting_id'] == 77
    assert body['start_at'] == '2030-01-07T09:00' and body['email_sent'] is True and body['source'] == 'franczyza'
    assert world['created'] == [('client', 'Jan', 101), ('meeting', 41, '2030-01-07T09:00')]


def test_booking_a_blocked_slot_is_refused_and_creates_nothing(app, world):
    write_schedule(world, [{'start': '2030-01-08T10:00', 'end': '2030-01-08T11:00'}])
    body, status = book(app, '2030-01-08T10:00')
    assert (body, status) == ({'success': False, 'error': 'Wybrany termin nie jest już dostępny.'}, 409)
    assert world['created'] == []
    assert book(app, '2030-01-08T09:00')[1] == 200


def test_booking_validation_errors_are_unchanged(app, world):
    assert book(app, '2030-01-07T09:00', first_name='')[1] == 400
    assert book(app, '2030-01-07T09:00', phone='', email='')[1] == 400
    assert book(app, '', )[1] == 400
    assert book(app, 'not a date')[1] == 400
    assert world['created'] == []


def test_booking_does_not_store_or_email_the_landing_url_or_referrer(app, world, monkeypatch):
    notes = []
    original = fs.create_client

    def create_client(payload, **kwargs):
        notes.append(payload["notes"])
        return original(payload, **kwargs)

    def send_email(**kwargs):
        notes.append(kwargs["note"])

    monkeypatch.setattr(fs, "create_client", create_client)
    monkeypatch.setattr(fs, "_send_franchise_meeting_email", send_email)
    assert book(app, '2030-01-07T09:00', landing_url="https://example.test/?private=1",
                referrer="https://example.test/?private=2")[1] == 200
    assert len(notes) == 2 and all("Źródło:" in note and "example.test" not in note for note in notes)
