"""Verifier for comm-001: Format Message for Multiple Channels."""

import json
from pathlib import Path

import pytest


@pytest.fixture
def workspace(request):
    return Path(request.config.getoption("--workspace"))


@pytest.fixture
def message(workspace):
    return json.loads((workspace / "message.json").read_text())


@pytest.fixture
def telegram(workspace):
    path = workspace / "outputs" / "telegram.txt"
    assert path.exists(), "telegram.txt not found"
    return path.read_text()


@pytest.fixture
def slack(workspace):
    path = workspace / "outputs" / "slack.json"
    assert path.exists(), "slack.json not found"
    return json.loads(path.read_text())


@pytest.fixture
def email(workspace):
    path = workspace / "outputs" / "email.txt"
    assert path.exists(), "email.txt not found"
    return path.read_text()


def test_outputs_directory_exists(workspace):
    assert (workspace / "outputs").is_dir(), "outputs/ directory not found"


def test_all_output_files_exist(workspace):
    for name in ["telegram.txt", "slack.json", "email.txt"]:
        assert (workspace / "outputs" / name).exists(), f"{name} not found"


def test_telegram_contains_subject(telegram, message):
    assert message["subject"] in telegram


def test_telegram_contains_body(telegram, message):
    assert message["body"] in telegram


def test_telegram_contains_all_links(telegram, message):
    for link in message["links"]:
        assert link["url"] in telegram
        assert link["label"] in telegram


def test_slack_has_blocks(slack):
    assert "blocks" in slack
    assert isinstance(slack["blocks"], list)
    assert len(slack["blocks"]) >= 3


def test_slack_header_block(slack, message):
    header_blocks = [b for b in slack["blocks"] if b.get("type") == "header"]
    assert len(header_blocks) >= 1
    header_text = json.dumps(header_blocks[0])
    assert message["subject"] in header_text


def test_slack_contains_body(slack, message):
    full_text = json.dumps(slack)
    assert message["body"] in full_text


def test_slack_contains_links(slack, message):
    full_text = json.dumps(slack)
    for link in message["links"]:
        assert link["url"] in full_text


def test_email_has_subject_header(email, message):
    assert f"Subject: {message['subject']}" in email


def test_email_has_from_header(email, message):
    assert message["sender"] in email


def test_email_has_recipients(email, message):
    for r in message["recipients"]:
        assert r in email


def test_email_contains_body(email, message):
    assert message["body"] in email


def test_email_contains_links(email, message):
    for link in message["links"]:
        assert link["url"] in email
        assert link["label"] in email
