"""Tests para build_vevent."""

from core.build_vevent import build_vevent


def _lines(text: str) -> list:
    """Parte la salida CRLF en lineas para asserts puntuales."""
    return text.split("\r\n")


def test_golden_evento_con_hora():
    out = build_vevent({
        "uid": "evt-demo",
        "summary": "Cita dentista",
        "start": "2026-06-20T17:00",
        "end": "2026-06-20T18:00",
        "location": "Clinica",
    })
    lines = _lines(out)
    assert lines[0] == "BEGIN:VCALENDAR"
    assert "VERSION:2.0" in lines
    assert "CALSCALE:GREGORIAN" in lines
    assert "BEGIN:VEVENT" in lines
    assert "UID:evt-demo" in lines
    assert "DTSTART:20260620T170000" in lines
    assert "DTEND:20260620T180000" in lines
    assert "SUMMARY:Cita dentista" in lines
    assert "LOCATION:Clinica" in lines
    assert "DTSTAMP:20260620T170000" in lines  # fallback determinista a DTSTART
    assert out.endswith("END:VCALENDAR\r\n")


def test_all_day():
    out = build_vevent({
        "summary": "Cumpleanos",
        "start": "2026-06-20",
        "all_day": True,
    })
    lines = _lines(out)
    assert "DTSTART;VALUE=DATE:20260620" in lines
    assert "DTEND;VALUE=DATE:20260621" in lines  # dia siguiente derivado
    assert "DTSTAMP:20260620" in lines


def test_rrule():
    out = build_vevent({
        "summary": "Standup",
        "start": "2026-06-22T09:00",
        "rrule": "FREQ=WEEKLY;BYDAY=MO",
    })
    lines = _lines(out)
    # El contenido del RRULE NO se escapa (sus ';' son separadores propios).
    assert "RRULE:FREQ=WEEKLY;BYDAY=MO" in lines


def test_uid_sintetico_determinista():
    e = {"summary": "Reunion", "start": "2026-06-20T17:00"}
    a = build_vevent(e)
    b = build_vevent(e)
    assert a == b  # mismo input -> misma salida
    uid_lines = [l for l in _lines(a) if l.startswith("UID:")]
    assert len(uid_lines) == 1
    assert uid_lines[0].startswith("UID:evt-")
    # Cambiar el summary cambia el UID sintetico.
    c = build_vevent({"summary": "Otra", "start": "2026-06-20T17:00"})
    uid_c = [l for l in _lines(c) if l.startswith("UID:")][0]
    assert uid_c != uid_lines[0]


def test_end_derivado_mas_una_hora():
    out = build_vevent({"summary": "X", "start": "2026-06-20T23:30"})
    lines = _lines(out)
    assert "DTSTART:20260620T233000" in lines
    assert "DTEND:20260621T003000" in lines  # cruza medianoche +1h


def test_utc_con_z():
    out = build_vevent({
        "summary": "Llamada",
        "start": "2026-06-20T17:00:00Z",
        "end": "2026-06-20T18:00:00Z",
    })
    lines = _lines(out)
    assert "DTSTART:20260620T170000Z" in lines
    assert "DTEND:20260620T180000Z" in lines


def test_escape_caracteres_especiales():
    out = build_vevent({
        "summary": "Reunion, urgente; con notas\nlinea2",
        "start": "2026-06-20T10:00",
        "location": "Sala A, planta 2",
        "description": "punto 1; punto 2",
    })
    lines = _lines(out)
    assert "SUMMARY:Reunion\\, urgente\\; con notas\\nlinea2" in lines
    assert "LOCATION:Sala A\\, planta 2" in lines
    assert "DESCRIPTION:punto 1\\; punto 2" in lines


def test_alarm():
    out = build_vevent({
        "summary": "Cita",
        "start": "2026-06-20T17:00",
        "alarm_minutes": 30,
    })
    lines = _lines(out)
    assert "BEGIN:VALARM" in lines
    assert "ACTION:DISPLAY" in lines
    assert "TRIGGER:-PT30M" in lines
    assert "END:VALARM" in lines
    # El VALARM va dentro del VEVENT (antes de END:VEVENT).
    assert lines.index("END:VALARM") < lines.index("END:VEVENT")


def test_claves_espanol_equivalentes():
    out = build_vevent({
        "titulo": "Evento ES",
        "inicio": "2026-06-20T12:00",
        "fin": "2026-06-20T13:00",
        "ubicacion": "Madrid",
        "descripcion": "desc",
        "recurrencia": "FREQ=DAILY",
        "recordatorio_min": 15,
    })
    lines = _lines(out)
    assert "SUMMARY:Evento ES" in lines
    assert "DTSTART:20260620T120000" in lines
    assert "DTEND:20260620T130000" in lines
    assert "LOCATION:Madrid" in lines
    assert "DESCRIPTION:desc" in lines
    assert "RRULE:FREQ=DAILY" in lines
    assert "TRIGGER:-PT15M" in lines


def test_falta_summary_lanza_valueerror():
    try:
        build_vevent({"start": "2026-06-20T10:00"})
        assert False, "deberia haber lanzado ValueError"
    except ValueError:
        pass


def test_falta_start_lanza_valueerror():
    try:
        build_vevent({"summary": "X"})
        assert False, "deberia haber lanzado ValueError"
    except ValueError:
        pass
