"""Archivo 1: barras, días ND, no numéricos, fechas duplicadas y recorte por fecha."""

from datetime import date

import pytest
from estudio01 import data_h10
from synth import h10_text

D = date


def test_nd_and_non_numeric_values_are_listed_and_are_not_bars():
    text = h10_text(
        [
            ("1999-01-04", "1.1812"),
            ("1999-01-05", "ND"),
            ("1999-01-06", "1.1636"),
            ("1999-01-07", "n.a."),
            ("1999-01-08", ""),
            ("1999-01-11", "1.1659"),
        ]
    )
    bars = data_h10.parse_h10(text)
    assert bars.dates == (D(1999, 1, 4), D(1999, 1, 6), D(1999, 1, 11))
    assert bars.prices == (1.1812, 1.1636, 1.1659)
    assert bars.skipped == (
        (D(1999, 1, 5), "ND"),
        (D(1999, 1, 7), "n.a."),
        (D(1999, 1, 8), ""),
    )


def test_a_value_with_a_comma_inside_quotes_is_not_numeric():
    text = h10_text([("1999-01-04", '"1,1812"'), ("1999-01-05", "1.17")])
    bars = data_h10.parse_h10(text)
    assert bars.dates == (D(1999, 1, 5),)
    assert bars.skipped == ((D(1999, 1, 4), "1,1812"),)


def test_the_file_is_clipped_by_date_in_memory():
    text = h10_text(
        [
            ("1998-12-31", "1.1"),
            ("1999-01-04", "1.2"),
            ("2026-09-30", "1.3"),
            ("2026-10-01", "1.4"),
        ]
    )
    bars = data_h10.parse_h10(text)
    assert bars.dates == (D(1999, 1, 4), D(2026, 9, 30))
    assert bars.prices == (1.2, 1.3)
    wider = data_h10.parse_h10(text, first_date=D(1998, 1, 1), last_date=D(2030, 1, 1))
    assert len(wider.dates) == 4


def test_a_duplicate_date_raises_even_outside_the_study_window():
    text = h10_text([("1998-12-31", "1.1"), ("1998-12-31", "1.2"), ("1999-01-04", "1.3")])
    with pytest.raises(data_h10.DuplicateDateError):
        data_h10.parse_h10(text)


def test_dates_out_of_order_raise():
    text = h10_text([("1999-01-05", "1.1"), ("1999-01-04", "1.2")])
    with pytest.raises(data_h10.UnexpectedFormatError):
        data_h10.parse_h10(text)


@pytest.mark.parametrize(
    "row",
    [
        "1999-01-04,0.5,1.1",  # faltan campos
        "1999-01-04,0.5,1.1,0.7,9",  # sobran campos
        "04/01/1999,0.5,1.1,0.7",  # fecha que no es AAAA-MM-DD
        "1999-02-30,0.5,1.1,0.7",  # fecha que no existe
        "\r\n1999-01-05,0.5,1.2,0.7",  # línea en blanco entre dos filas de datos
    ],
)
def test_rows_with_an_uncovered_format_stop_the_code(row):
    text = h10_text([("1999-01-04", "1.1")]) + "\r\n" + row
    with pytest.raises(data_h10.UnexpectedFormatError):
        data_h10.parse_h10(text)


def test_the_euro_column_is_found_by_its_identifier_not_by_position():
    header = [
        '"Series Description","Euro-Area Euro","Other"',
        '"Unit:","Currency","Currency"',
        '"Multiplier:","1","1"',
        '"Currency:","EUR","XXX"',
        '"Unique Identifier: ","H10/H10/RXI$US_N.B.EU","H10/H10/OTHER"',
        '"Time Period","RXI$US_N.B.EU","OTHER"',
    ]
    text = "\r\n".join([*header, "1999-01-04,1.1812,9.9"])
    bars = data_h10.parse_h10(text)
    assert bars.prices == (1.1812,)
    swapped = text.replace('"RXI$US_N.B.EU","OTHER"', '"OTHER","RXI$US_N.B.EU"').replace(
        "1.1812,9.9", "9.9,1.1812"
    )
    assert data_h10.parse_h10(swapped).prices == (1.1812,)


def test_missing_or_repeated_euro_identifier_stops_the_code():
    text = h10_text([("1999-01-04", "1.1")])
    with pytest.raises(data_h10.UnexpectedFormatError):
        data_h10.parse_h10(text.replace("RXI$US_N.B.EU", "RXI$US_N.B.XX"))
    repeated = text.replace('"RXI$US_N.B.NZ"', '"RXI$US_N.B.EU"')
    with pytest.raises(data_h10.UnexpectedFormatError):
        data_h10.parse_h10(repeated)
    with pytest.raises(data_h10.UnexpectedFormatError):  # solo cabecera, sin filas de datos
        data_h10.parse_h10(h10_text([]))


def test_load_bars_reads_the_file_as_strict_utf8(tmp_path):
    good = tmp_path / "good.csv"
    good.write_bytes(h10_text([("1999-01-04", "1.1812")]).encode("utf-8"))
    assert data_h10.load_bars(good).prices == (1.1812,)
    bad = tmp_path / "bad.csv"
    bad.write_bytes(h10_text([("1999-01-04", "1.1812")]).encode("utf-8") + b"\xff")
    with pytest.raises(UnicodeDecodeError):
        data_h10.load_bars(bad)


def test_a_leading_bom_and_a_missing_final_newline_do_not_change_the_bars():
    """El archivo real viene con BOM UTF-8, CRLF y sin salto final: se lee igual que sin BOM."""
    text = h10_text([("1999-01-04", "1.1812"), ("1999-01-05", "ND"), ("1999-01-06", "1.1636")])
    assert "\r\n" in text and not text.endswith("\n")
    assert data_h10.parse_h10("﻿" + text) == data_h10.parse_h10(text)
    assert data_h10.parse_h10("﻿" + text).prices == (1.1812, 1.1636)
