"""A column the report marks restated is the same line printed again for that year: a dated observation, not a
segment, not a new row. Covers extraction, merge, raw table and the cell view's publications."""
from app.ocr.services import csv_service
from app.ocr.services import extraction_service as ext
from app.ocr.services import series_linker as sl
from app.ocr import router

PAGE = """# Statement of Financial Position

| Particulars | Notes | 30-Jun-23 | 30-Jun-22 | 1st July 2022 (Re-Stated) |
|---|---|---|---|---|
| Inventories | 4 | 178,611,529 | 181,085,873 | 181,085,873 |
| Trade and Other Receivables | 5 | 223,651,430 | 213,933,121 | 218,933,121 |
"""

RESTATED = {"t": [
    {"n": 1, "s": "B", "sc": "S", "u": "BDT", "m": 1, "lc": 1, "nc": 2,
     "y": [{"c": 3, "y": 2023, "d": "2023-06-30"}, {"c": 4, "y": 2022, "d": "2022-06-30"},
           {"c": 5, "y": 2022, "d": "2022-07-01", "rs": 1}],
     "sec": [{"a": 1, "b": 2, "t": "Current Assets"}],
     "r": [{"r": 1, "c": "Inventories", "l": "L"}, {"r": 2, "c": "Trade and Other Receivables", "l": "L"}]},
]}


def test_restated_column_is_not_a_segment_and_keeps_its_date():
    items = ext.decode_compact_extraction(RESTATED, PAGE)
    assert len(items) == 2                                    # one line per row, no row per column header
    assert all(i["scope"]["segment"] is None for i in items)
    receivables = next(i for i in items if i["raw_field"] == "Trade and Other Receivables")
    by_col = {o["table_col"]: o for o in receivables["data"]}
    assert (by_col[4]["year"], by_col[4]["date"], by_col[4]["restated"]) == (2022, "2022-06-30", 0)
    assert (by_col[5]["year"], by_col[5]["date"], by_col[5]["restated"]) == (2022, "2022-07-01", 1)


def test_same_year_columns_without_the_restated_mark_are_still_segments():
    specs = [{"col": 3, "y": 2013}, {"col": 4, "y": 2013}]
    header = [["Particulars", "Note", "Conventional Taka 2013", "Islamic Taka 2013"]]
    assert ext._same_year_segments(specs, {3: 2013, 4: 2013}, header) == {3: "Conventional", 4: "Islamic"}
    # the same two columns with one marked restated: nothing is a segment
    specs[1]["rs"] = 1
    assert ext._same_year_segments(specs, {3: 2013, 4: 2013}, header) == {}


def _metric(fy, row_values, row=1):
    """row_values: [(year, date, restated, value, col)]"""
    return {"id": hash((fy, row)) % 10**8, "fiscal_year": fy, "page_number": 5, "statement_type": "BALANCE_SHEET",
            "concept_name": "Trade and Other Receivables", "category": "Current Assets", "aggregation_level": "LINE_ITEM",
            "scope": "STANDALONE", "entity": None, "segment": None, "temporal_state": "POINT_IN_TIME", "action": None,
            "metric_type": "CURRENCY", "qualifier": None, "raw_field": "Trade and Other Receivables",
            "field": "Trade and Other Receivables", "tag": "FINANCIAL_METRIC",
            "data": [{"year": y, "date": d, "restated": r, "numeric_value": v, "unit": "BDT", "multiplier": 1.0,
                      "table_num": 1, "table_row": row, "table_col": c} for (y, d, r, v, c) in row_values]}


def _series(metrics):
    nodes = sl.build_nodes(metrics, {})
    res = sl.link_company(nodes, [], judge=None)
    series, _, review = sl.build_series(nodes, res["links"])
    return series, review


def test_merge_takes_the_restated_value_and_keeps_the_earlier_print():
    reports = [
        _metric("2021-22", [(2022, "2022-06-30", 0, 213933121, 3)]),
        _metric("2022-23", [(2023, "2023-06-30", 0, 223651430, 3), (2022, "2022-06-30", 0, 213933121, 4),
                            (2022, "2022-07-01", 1, 218933121, 5)]),
    ]
    series, review = _series(reports)
    assert len(series) == 1                                   # one line, not one per column header
    res = sl.resolve_series_values(series[0])
    assert res["values"][2022] == 218933121                   # the 1 July restated figure stays
    assert res["values"][2023] == 223651430
    assert res["restate"]["2022"]["original_value"] == 213933121
    assert res["restate"]["2022"]["restated_value"] == 218933121
    assert not [r for r in review if r["kind"] in ("VALUE_CONFLICT",)]
    assert "INTRA_NODE_CONFLICT" not in series[0]["nodes"][-1]["flags"]


def test_a_later_report_printing_the_year_again_wins_over_the_restated_figure():
    reports = [
        _metric("2022-23", [(2023, "2023-06-30", 0, 223651430, 3), (2022, "2022-06-30", 0, 213933121, 4),
                            (2022, "2022-07-01", 1, 218933121, 5)]),
        _metric("2023-24", [(2024, "2024-06-30", 0, 202261327, 3), (2023, "2023-06-30", 0, 223651431, 4)]),
    ]
    series, _ = _series(reports)
    res = sl.resolve_series_values(series[0])
    assert res["values"][2022] == 218933121                   # not printed again: the restated figure remains
    assert res["values"][2023] == 223651431                   # printed again by the later report: that one


def test_raw_columns_are_named_by_date_when_a_report_prints_a_year_twice():
    metrics = [_metric("2022-23", [(2023, "2023-06-30", 0, 223651430, 3), (2022, "2022-06-30", 0, 213933121, 4),
                                   (2022, "2022-07-01", 1, 218933121, 5)]),
               _metric("2021-22", [(2022, "2022-06-30", 0, 213933121, 3)], row=2)]
    for m in metrics:
        m["page_number"] = 5
    res = csv_service.build_raw_csv_from_metrics(metrics)
    cols = {c["key"]: c for c in res["raw_columns"]}
    assert "2022-23__2023" in cols                            # years printed once keep their plain key
    assert "2021-22__2022" in cols
    assert cols["2022-23__2022@2022-06-30"]["header"] == "2022-06-30"
    assert cols["2022-23__2022@2022-07-01"]["restated"] is True
    assert cols["2022-23__2022@2022-07-01"]["observation_date"] == "2022-07-01"
    assert cols["2022-23__2022@2022-06-30"]["restated"] is False


def test_cell_view_lists_the_restated_print_of_the_same_report_as_restated():
    def rec(report, value, restated, date):
        return {"report_year": report, "page_number": 5, "table_num": 1, "effective_value": value,
                "restated": restated, "date": date, "raw_field": "x", "field": "x"}
    records = [rec("2021-22", 213933121.0, False, "2022-06-30"), rec("2022-23", 213933121.0, False, "2022-06-30"),
               rec("2022-23", 218933121.0, True, "2022-07-01")]
    reps = router._publications(records)
    assert [r["date"] for r in reps] == ["2022-06-30", "2022-06-30", "2022-07-01"]
    assert router._publication_statuses(reps) == ["ORIGINAL_STATED", "RESTATED", "RESTATED"]
    assert router._restatement_dots(records) == ["green", "yellow"]
