#!/usr/bin/env python3
"""Painel de acurácia reproduzível (#6231): arquivo único, só stdlib.

Compara uma amostra aleatória estratificada do que a API pública da OBM serve com
o arquivo oficial aberto da B3 ou da CVM, nunca com outra rota da OBM. A mesma
semente (padrão: a data como AAAAMMDD) devolve a mesma amostra.

Este é o mesmo arquivo que o worker importa (``app.accuracy.engine``) e que o site
serve em /accuracy/run.py. Uso, com Python 3.12 e sem instalar nada:

    OBM_API_KEY=... python3 run.py --date 2026-11-26 --out resultado.json
"""

from __future__ import annotations

import argparse
import base64
import csv
import hashlib
import io
import json
import os
import random
import re
import sys
import time
import urllib.error
import urllib.request
import zipfile
from collections import Counter
from collections.abc import Callable, Iterable
from dataclasses import asdict, dataclass
from datetime import date, datetime, timedelta
from decimal import Decimal, InvalidOperation
from typing import Any
from urllib.parse import urlencode


# --- HTTP ---

USER_AGENT = "obm-accuracy/1 (+https://obm.com.br/api/qualidade)"
MIN_INTERVAL_SECONDS = 0.3
ATTEMPTS = 3
# Espera máxima por um Retry-After. Acima disso (cota diária estourada) não vale
# segurar o processo: a chamada falha e quem roda decide quando tentar de novo.
MAX_RETRY_AFTER_SECONDS = 120.0

BytesFetcher = Callable[[str], bytes]
JsonFetcher = Callable[[str], Any]


def _seconds(raw: Any) -> float | None:
    try:
        value = float(raw)
    except (TypeError, ValueError):
        return None
    return value if value >= 0 else None


class Client:
    """Fetchers com throttle. ``headers`` vai em toda chamada (ex.: Authorization).

    Respeita os limites da API pública: com ``X-RateLimit-Remaining: 0`` espera o
    ``Retry-After`` antes da próxima chamada; num 429 espera o ``Retry-After`` e tenta
    de novo (até ``MAX_RETRY_AFTER_SECONDS``; acima disso a falha sobe).
    """

    def __init__(self, headers: dict[str, str] | None = None, *, timeout: float = 120.0):
        self._headers = {"User-Agent": USER_AGENT, **(headers or {})}
        self._timeout = timeout
        self._last = 0.0
        self._not_before = 0.0

    def _wait_turn(self) -> None:
        now = time.monotonic()
        wait = max(MIN_INTERVAL_SECONDS - (now - self._last), self._not_before - now)
        if wait > 0:
            time.sleep(wait)

    def _note(self, headers: Any) -> None:
        self._last = time.monotonic()
        retry = _seconds(headers.get("Retry-After"))
        if str(headers.get("X-RateLimit-Remaining")) == "0" and retry is not None:
            pause = min(retry, MAX_RETRY_AFTER_SECONDS)
            self._not_before = max(self._not_before, self._last + pause)

    def get_bytes(self, url: str) -> bytes:
        last_error: Exception | None = None
        for attempt in range(ATTEMPTS):
            self._wait_turn()
            try:
                request = urllib.request.Request(url, headers=self._headers)
                with urllib.request.urlopen(request, timeout=self._timeout) as response:
                    body: bytes = response.read()
                    self._note(response.headers)
                return body
            except urllib.error.HTTPError as error:
                headers = error.headers or {}
                self._note(headers)
                if error.code == 429:
                    retry = _seconds(headers.get("Retry-After"))
                    if retry is not None and retry > MAX_RETRY_AFTER_SECONDS:
                        raise
                    last_error = error
                    pause = retry if retry is not None else float(2**attempt)
                    self._not_before = max(self._not_before, time.monotonic() + pause)
                    continue
                if error.code < 500:
                    raise
                last_error = error
            except (urllib.error.URLError, TimeoutError) as error:
                self._last = time.monotonic()
                last_error = error
            time.sleep(2**attempt)
        assert last_error is not None
        raise last_error

    def get_json(self, url: str) -> Any:
        body = self.get_bytes(url)
        return json.loads(body) if body.strip() else None


def load_official(fetch: BytesFetcher, url: str, parse: Callable[[bytes], Any]) -> Any:
    """Lê e interpreta um arquivo oficial; ``None`` só para arquivo ausente ou corrompido.

    404 (dia sem pregão, mês ainda não publicado) e ``BadZipFile`` viram "não comparável".
    Qualquer outra falha (5xx, timeout, DNS, 403) sobe: fonte fora do ar não pode virar
    taxa de acerto.
    """
    try:
        return parse(fetch(url))
    except urllib.error.HTTPError as error:
        if error.code == 404:
            return None
        raise
    except zipfile.BadZipFile:
        return None


# --- Fontes oficiais ---

COTAHIST_DAILY_URL = "https://bvmf.bmfbovespa.com.br/InstDados/SerHist/COTAHIST_D{day}.ZIP"
CVM_INF_DIARIO_URL = (
    "https://dados.cvm.gov.br/dados/FI/DOC/INF_DIARIO/DADOS/inf_diario_fi_{month}.zip"
)
CVM_DFP_URL = "https://dados.cvm.gov.br/dados/CIA_ABERTA/DOC/DFP/DADOS/dfp_cia_aberta_{year}.zip"
B3_COMPANIES_URL = "https://sistemaswebb3-listados.b3.com.br/listedCompaniesProxy/CompanyCall"

MONEY_SCALE = {"MIL": Decimal("1000"), "UNIDADE": Decimal("1")}


def cotahist_daily_url(day: date) -> str:
    return COTAHIST_DAILY_URL.format(day=day.strftime("%d%m%Y"))


def inf_diario_url(day: date) -> str:
    return CVM_INF_DIARIO_URL.format(month=day.strftime("%Y%m"))


def dfp_url(year: int) -> str:
    return CVM_DFP_URL.format(year=year)


def digits(value: str | None) -> str:
    return re.sub(r"\D", "", value or "")


def parse_decimal(raw: Any) -> Decimal | None:
    """Decimal pt-BR (``1.234,56``) ou canônico; ``None`` se inválido."""
    text = str(raw if raw is not None else "").strip()
    if not text:
        return None
    if "," in text:
        text = text.replace(".", "").replace(",", ".")
    try:
        return Decimal(text)
    except InvalidOperation:
        return None


def parse_br_date(raw: Any) -> date | None:
    text = str(raw if raw is not None else "").strip()
    for fmt in ("%d/%m/%Y", "%Y-%m-%d"):
        try:
            return datetime.strptime(text, fmt).date()
        except ValueError:
            continue
    return None


def _open_members(payload: bytes) -> zipfile.ZipFile:
    return zipfile.ZipFile(io.BytesIO(payload))


def cotahist_closes(payload: bytes) -> dict[str, Decimal]:
    """Ticker -> fechamento bruto (PREULT, 2 casas) do mercado à vista (TPMERC 010)."""
    closes: dict[str, Decimal] = {}
    with _open_members(payload) as archive:
        for name in archive.namelist():
            with archive.open(name) as handle:
                for raw in io.TextIOWrapper(handle, encoding="latin-1"):
                    if raw[0:2] != "01" or raw[24:27] != "010":
                        continue
                    ticker = raw[12:24].strip()
                    closes[ticker] = Decimal(int(raw[108:121])) / Decimal(100)
    return closes


def inf_diario_quotas(
    payload: bytes, wanted: Iterable[tuple[str, date]]
) -> dict[tuple[str, date], set[Decimal]]:
    """(CNPJ só dígitos, data) -> conjunto de VL_QUOTA do Informe Diário.

    Conjunto com mais de um valor significa subclasses diferentes sob o mesmo
    CNPJ: o ponto não é comparável e quem chama o separa.
    """
    keys = set(wanted)
    found: dict[tuple[str, date], set[Decimal]] = {}
    with _open_members(payload) as archive:
        for name in archive.namelist():
            with archive.open(name) as handle:
                reader = csv.DictReader(io.TextIOWrapper(handle, encoding="latin-1"), delimiter=";")
                for row in reader:
                    cnpj = digits(row.get("CNPJ_FUNDO_CLASSE") or row.get("CNPJ_FUNDO"))
                    day = parse_br_date(row.get("DT_COMPTC"))
                    if day is None or (cnpj, day) not in keys:
                        continue
                    quota = parse_decimal(row.get("VL_QUOTA"))
                    if quota is not None:
                        found.setdefault((cnpj, day), set()).add(quota)
    return found


def dfp_values(
    payload: bytes,
    wanted: Iterable[tuple[str, str, str, date, str]],
) -> dict[tuple[str, str, str, date, str], Decimal]:
    """(kind, escopo, CNPJ, DT_REFER, CD_CONTA) -> valor em unidades de BRL.

    ``kind`` é DRE, BPA ou BPP e ``escopo`` é ``con`` ou ``ind``. Vale a última
    VERSAO do documento, exercício ÚLTIMO e a janela mais longa (DRE traz o
    acumulado e o trimestre). ``ESCALA_MOEDA`` MIL vira unidade; o grupo 3.99
    (lucro por ação) fica em reais por ação, como a CVM publica.
    """
    keys = set(wanted)
    best: dict[tuple[str, str, str, date, str], tuple[int, str, Decimal]] = {}
    groups = {(kind, scope) for kind, scope, *_ in keys}
    with _open_members(payload) as archive:
        names = {name.rsplit("/", 1)[-1]: name for name in archive.namelist()}
        for kind, scope in groups:
            member = next(
                (full for short, full in names.items() if f"_{kind}_{scope}_" in short), None
            )
            if member is None:
                continue
            with archive.open(member) as handle:
                reader = csv.DictReader(io.TextIOWrapper(handle, encoding="latin-1"), delimiter=";")
                for row in reader:
                    if row.get("ORDEM_EXERC") != "ÚLTIMO":
                        continue
                    ref = parse_br_date(row.get("DT_REFER"))
                    key = (kind, scope, digits(row.get("CNPJ_CIA")), ref, row.get("CD_CONTA", ""))
                    if key not in keys:
                        continue
                    amount = parse_decimal(row.get("VL_CONTA"))
                    if amount is None:
                        continue
                    if not key[4].startswith("3.99"):
                        amount *= MONEY_SCALE.get(row.get("ESCALA_MOEDA", ""), Decimal("1"))
                    version = int(row.get("VERSAO") or 0)
                    # Janela mais longa = menor DT_INI_EXERC (texto ISO ordena como data).
                    window = row.get("DT_INI_EXERC") or "9999-12-31"
                    current = best.get(key)
                    if (
                        current is None
                        or version > current[0]
                        or (version == current[0] and window < current[1])
                    ):
                        best[key] = (version, window, amount)
    return {key: value[2] for key, value in best.items()}


def b3_dividends_url(function: str, params: dict[str, Any]) -> str:
    encoded = base64.b64encode(json.dumps(params).encode("utf-8")).decode("ascii")
    return f"{B3_COMPANIES_URL}/{function}/{encoded}"


def normalize_trading_name(raw: str | None) -> str | None:
    """Forma que a B3 aceita: caixa alta e sem a primeira ocorrência de `` -_/``."""
    if raw is None:
        return None
    name = raw.upper().strip()
    for char in (" ", "-", "_", "/"):
        if char in name:
            name = name.replace(char, "", 1)
            break
    return name or None


# --- Amostra e comparação ---

MATCH = "match"
DIVERGED = "diverged"
NOT_COMPARABLE = "not_comparable"

PRICE_TOLERANCE = Decimal("0.00005")  # 4 casas
QUOTA_TOLERANCE = Decimal("0.000000005")  # 8 casas
DIVIDEND_TOLERANCE = Decimal("0.0000005")  # 6 casas
DIVIDEND_EX_WINDOW_DAYS = 5

PRICE_RULE = "Fechamento bruto igual até 4 casas decimais."
DIVIDEND_RULE = (
    "Valor por ação igual até 6 casas; ex-date entre 1 e 5 dias corridos depois da data-com."
)
STATEMENT_RULE = "Valor exato em unidades de BRL (escala aplicada), mesma conta, período e escopo."
QUOTA_RULE = "Valor da cota igual até 8 casas decimais."

PN_CLASSES = {"PN", "PNA", "PNB", "PNC", "PND"}


@dataclass
class Point:
    key: str
    status: str
    obm: str | None
    official: str | None
    official_url: str
    note: str = ""


@dataclass
class Sizes:
    equity_prices: int = 30
    corporate_events: int = 20
    statements: int = 20
    fund_quotas: int = 30

    def limited(self, size: int) -> Sizes:
        """No máximo ``size`` pontos por dataset, nunca mais que a amostra cheia."""
        return Sizes(
            min(size, self.equity_prices),
            min(size, self.corporate_events),
            min(size, self.statements),
            min(size, self.fund_quotas),
        )


class Api:
    """API pública da OBM: conta as chamadas e busca o universo de ações uma vez só."""

    def __init__(self, base: str, fetch_json: JsonFetcher):
        self._base = base.rstrip("/")
        self._fetch = fetch_json
        self._universe: list[dict[str, Any]] | None = None
        self.calls = 0

    def universe(self) -> list[dict[str, Any]]:
        if self._universe is None:
            items = self.pages("/v1/equities")
            self._universe = sorted(
                (i for i in items if i.get("ticker")), key=lambda i: i["ticker"]
            )
        return list(self._universe)

    def get(self, path: str, **params: Any) -> Any:
        self.calls += 1
        query = urlencode({k: v for k, v in params.items() if v is not None})
        return self._fetch(f"{self._base}{path}" + (f"?{query}" if query else ""))

    def pages(self, path: str, **params: Any) -> list[Any]:
        items: list[Any] = []
        page = 1
        while True:
            body = self.get(path, page=page, page_size=200, **params)
            items.extend(body.get("data") or [])
            total = (body.get("meta") or {}).get("total", 0)
            if page * 200 >= total:
                return items
            page += 1


def rng_for(seed: int, dataset: str) -> random.Random:
    return random.Random(f"{seed}:{dataset}")


def weekdays(start: date, end: date) -> list[date]:
    days = (start + timedelta(days=n) for n in range((end - start).days + 1))
    return [d for d in days if d.weekday() < 5]


def _dec(value: Any) -> Decimal:
    return Decimal(repr(value)) if isinstance(value, float) else Decimal(str(value))


def _latest_reference(api: Api) -> date:
    body = api.get("/v1/equities/PETR4/prices", page_size=1)
    return date.fromisoformat(body["reference_date"])


def split_evenly(total: int, parts: int) -> list[int]:
    """Reparte ``total`` em ``parts`` fatias, as primeiras com uma unidade a mais."""
    return [total // parts + (1 if index < total % parts else 0) for index in range(parts)]


def _terciles(items: list[dict[str, Any]], rng: random.Random, count: int) -> list[dict[str, Any]]:
    ranked = sorted(
        (i for i in items if i.get("avg_volume_30d_brl")),
        key=lambda i: (i["avg_volume_30d_brl"], i["ticker"]),
    )
    third = len(ranked) // 3
    picked: list[dict[str, Any]] = []
    bands = (ranked[:third], ranked[third : 2 * third], ranked[2 * third :])
    for band, per in zip(bands, split_evenly(count, 3), strict=True):
        picked.extend(rng.sample(band, min(per, len(band))))
    return picked


def check_equity_prices(
    api: Api, fetch_bytes: BytesFetcher, seed: int, count: int, today: date
) -> list[Point]:
    rng = rng_for(seed, "equity_prices")
    latest = _latest_reference(api)
    days = rng.sample(weekdays(latest - timedelta(days=24), latest), 5)
    sample = _terciles(api.universe(), rng, count)
    closes: dict[date, dict[str, Decimal] | None] = {}
    points: list[Point] = []
    for item in sample:
        ticker, day = item["ticker"], rng.choice(days)
        url = cotahist_daily_url(day)
        if day not in closes:
            closes[day] = load_official(fetch_bytes, url, cotahist_closes)  # None: sem pregão
        key = f"{ticker} {day.isoformat()}"
        official_table = closes[day]
        if official_table is None or ticker not in official_table:
            points.append(Point(key, NOT_COMPARABLE, None, None, url, "sem linha no arquivo B3"))
            continue
        official = official_table[ticker]
        rows = api.get(f"/v1/equities/{ticker}/prices", start=day, end=day)["data"]
        raw = rows[0].get("close_unadjusted") if rows else None
        if raw is None:
            points.append(Point(key, DIVERGED, None, str(official), url, "OBM sem fechamento"))
            continue
        diff = abs(_dec(raw) - official)
        status = MATCH if diff < PRICE_TOLERANCE else DIVERGED
        points.append(Point(key, status, str(raw), str(official), url))
    return points


def _json_or_none(fetch: JsonFetcher, url: str) -> Any:
    """JSON da B3; 404 vira ``None`` (emissor desconhecido), qualquer outra falha sobe."""
    try:
        return fetch(url)
    except urllib.error.HTTPError as error:
        if error.code == 404:
            return None
        raise


def _b3_rows(api_fetch: JsonFetcher, issuer: str, cache: dict[str, list[dict[str, Any]] | None]):
    if issuer in cache:
        return cache[issuer]
    head = _json_or_none(
        api_fetch,
        b3_dividends_url("GetListedSupplementBDR", {"issuingCompany": issuer, "language": "pt-br"}),
    )
    head = head[0] if isinstance(head, list) and head else head
    name = normalize_trading_name((head or {}).get("tradingName")) if head else None
    if not name:
        cache[issuer] = None
        return None
    rows: list[dict[str, Any]] = []
    page = 1
    while True:
        body = _json_or_none(
            api_fetch,
            b3_dividends_url(
                "GetListedCashDividends",
                {"language": "pt-br", "pageNumber": page, "pageSize": 120, "tradingName": name},
            ),
        )
        if not body:
            break
        rows.extend(body.get("results") or [])
        if page >= int((body.get("page") or {}).get("totalPages") or 0):
            break
        page += 1
    cache[issuer] = rows
    return rows


def check_corporate_events(
    api: Api, b3_fetch_json: JsonFetcher, seed: int, count: int
) -> list[Point]:
    rng = rng_for(seed, "corporate_events")
    universe = [i for i in api.universe() if i["ticker"][-1] in "34"]
    cache: dict[str, list[dict[str, Any]] | None] = {}
    points: list[Point] = []
    for item in rng.sample(universe, min(len(universe), count * 3)):
        if len(points) >= count:
            break
        ticker = item["ticker"]
        events = [
            e
            for e in api.get(f"/v1/equities/{ticker}/corporate-events", page_size=200)["data"]
            if e.get("value_per_share") is not None and e.get("ex_date") and not e.get("ratio_to")
        ]
        if not events:
            continue
        event = rng.choice(sorted(events, key=lambda e: (e["ex_date"], e["value_per_share"])))
        ex_date = date.fromisoformat(event["ex_date"])
        key = f"{ticker} ex {ex_date.isoformat()}"
        url = f"{B3_COMPANIES_URL}/GetListedCashDividends"
        rows = _b3_rows(b3_fetch_json, ticker[:4], cache)
        if rows is None:
            points.append(Point(key, NOT_COMPARABLE, None, None, url, "emissor sem tradingName"))
            continue
        classes = {"ON"} if ticker.endswith("3") else PN_CLASSES
        near: list[Decimal] = []
        matched = False
        for row in rows:
            com = parse_br_date(row.get("lastDatePriorEx"))
            amount = parse_decimal(row.get("valueCash"))
            if com is None or amount is None or row.get("typeStock") not in classes:
                continue
            if 1 <= (ex_date - com).days <= DIVIDEND_EX_WINDOW_DAYS:
                near.append(amount)
                if abs(_dec(event["value_per_share"]) - amount) <= DIVIDEND_TOLERANCE:
                    matched = True
        official = ", ".join(str(v) for v in sorted(set(near))) or None
        status = MATCH if matched else DIVERGED
        note = "" if matched or near else "sem linha B3 com data-com na janela"
        points.append(Point(key, status, str(event["value_per_share"]), official, url, note))
    return points


def check_statements(
    api: Api, fetch_bytes: BytesFetcher, seed: int, count: int, today: date
) -> list[Point]:
    rng = rng_for(seed, "statements")
    candidates = api.universe()
    rng.shuffle(candidates)
    picks: list[tuple[str, str, str, date, str, Decimal, str, str, str | None]] = []
    for item in candidates:
        if len(picks) >= count:
            break
        ticker = item["ticker"]
        cnpj = digits((api.get(f"/v1/equities/{ticker}")["data"] or {}).get("company_cnpj"))
        if not cnpj:
            continue
        kind_type = "income_statement" if len(picks) % 2 == 0 else "balance_sheet"
        statements = [
            s
            for s in api.get(f"/v1/equities/{ticker}/statements", type=kind_type, page_size=10)[
                "data"
            ]
            if s.get("fiscal_quarter") is None and int(s["fiscal_year"]) >= today.year - 3
        ]
        if not statements:
            continue
        statement = rng.choice(
            sorted(statements, key=lambda s: (s["reference_date"], s["value_scope"]))
        )
        lines = [ln for ln in statement["lines"] if ln.get("value") is not None]
        if not lines:
            continue
        line = rng.choice(sorted(lines, key=lambda ln: ln["account_code"]))
        code = line["account_code"]
        kind = (
            "DRE" if kind_type == "income_statement" else ("BPA" if code.startswith("1") else "BPP")
        )
        scope = "con" if statement["value_scope"] == "consolidated" else "ind"
        year = int(statement["fiscal_year"])
        link = statement.get("source_document_url") or statement.get("source_url") or dfp_url(year)
        picks.append(
            (
                ticker,
                kind,
                scope,
                date.fromisoformat(statement["reference_date"]),
                code,
                _dec(line["value"]),
                link,
                cnpj,
                statement.get("source_sha256"),
            )
        )
    by_year: dict[int, list[tuple]] = {}
    for pick in picks:
        by_year.setdefault(pick[3].year, []).append(pick)
    points: list[Point] = []
    for year, group in sorted(by_year.items()):
        url = dfp_url(year)
        wanted = [(p[1], p[2], p[7], p[3], p[4]) for p in group]
        loaded = load_official(
            fetch_bytes,
            url,
            lambda payload, wanted=wanted: (
                hashlib.sha256(payload).hexdigest(),
                dfp_values(payload, wanted),
            ),
        )
        digest, official = loaded if loaded is not None else (None, {})
        for ticker, kind, scope, ref, code, value, link, cnpj, served_sha in group:
            key = f"{ticker} {kind}/{scope} {ref.isoformat()} {code}"
            found = official.get((kind, scope, cnpj, ref, code))
            if found is None:
                points.append(
                    Point(key, NOT_COMPARABLE, str(value), None, link, "sem linha no CSV da CVM")
                )
                continue
            if found == value:
                points.append(Point(key, MATCH, str(value), str(found), link))
                continue
            note = ""
            if served_sha and digest:
                same = served_sha.lower() == digest
                note = (
                    "arquivo da CVM igual ao coletado"
                    if same
                    else "arquivo da CVM mudou desde a coleta"
                )
            points.append(Point(key, DIVERGED, str(value), str(found), link, note))
    return points


def check_fund_quotas(
    api: Api, fetch_bytes: BytesFetcher, seed: int, count: int, today: date
) -> list[Point]:
    rng = rng_for(seed, "fund_quotas")
    first = api.get("/v1/funds", type="FI", page=1, page_size=200)
    last_page = max(1, -(-int((first.get("meta") or {}).get("total", 0)) // 200))
    pool = list(first["data"])
    for page in rng.sample(range(2, last_page + 1), min(2, max(0, last_page - 1))):
        pool.extend(api.get("/v1/funds", type="FI", page=page, page_size=200)["data"])
    pool = [f for f in pool if f.get("nav_per_share") is not None and f.get("fund_class")]
    classes = Counter(f["fund_class"] for f in pool)
    chosen = sorted(classes, key=lambda c: (-classes[c], c))[:3]
    anchor = today - timedelta(days=45)
    month_days = weekdays(
        anchor.replace(day=1),
        (anchor.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1),
    )
    sample: list[tuple[str, str, date]] = []
    per_class = split_evenly(count, 3)
    for fund_class in chosen:
        members = sorted(
            (f for f in pool if f["fund_class"] == fund_class), key=lambda f: f["cnpj"]
        )
        for fund in rng.sample(members, min(per_class[chosen.index(fund_class)], len(members))):
            sample.append((fund["cnpj"], fund_class, rng.choice(month_days)))
    url = inf_diario_url(month_days[0])
    wanted_quotas = [(digits(c), d) for c, _, d in sample]
    official = (
        load_official(fetch_bytes, url, lambda payload: inf_diario_quotas(payload, wanted_quotas))
        or {}
    )
    points: list[Point] = []
    for cnpj, fund_class, day in sample:
        key = f"{cnpj} {day.isoformat()} ({fund_class})"
        values = official.get((digits(cnpj), day))
        if not values or len(values) > 1:
            note = "sem linha no Informe Diário" if not values else "subclasses com cotas distintas"
            points.append(Point(key, NOT_COMPARABLE, None, None, url, note))
            continue
        expected = next(iter(values))
        rows = api.get(f"/v1/funds/{cnpj}/nav", start=day, end=day)["data"]
        raw = rows[0].get("nav_per_share") if rows else None
        if raw is None:
            points.append(Point(key, DIVERGED, None, str(expected), url, "OBM sem cota"))
            continue
        status = MATCH if abs(_dec(raw) - expected) <= QUOTA_TOLERANCE else DIVERGED
        points.append(Point(key, status, str(raw), str(expected), url))
    return points


def summarize(
    dataset: str, label: str, rule: str, source: str, points: list[Point]
) -> dict[str, Any]:
    compared = [p for p in points if p.status != NOT_COMPARABLE]
    matched = sum(p.status == MATCH for p in compared)
    return {
        "dataset": dataset,
        "label": label,
        "source": source,
        "tolerance": rule,
        "sampled": len(points),
        "compared": len(compared),
        "matched": matched,
        "match_ratio": round(matched / len(compared), 4) if compared else None,
        "not_comparable": len(points) - len(compared),
        "divergences": [asdict(p) for p in points if p.status == DIVERGED],
    }


# --- Rodada e linha de comando ---

SCHEMA_VERSION = 1
DEFAULT_API_BASE = "https://api.obm.com.br"
# Padrão da linha de comando: cabe no plano grátis (10 por minuto, 200 por dia), com
# cerca de 60 chamadas à API. A task de produção usa a amostra cheia (``Sizes()``).
DEFAULT_SAMPLE_SIZE = 5


def default_seed(run_date: date) -> int:
    return int(run_date.strftime("%Y%m%d"))


def run(
    *,
    api_base: str,
    api_fetch_json: JsonFetcher,
    fetch_bytes: BytesFetcher,
    b3_fetch_json: JsonFetcher,
    run_date: date,
    seed: int | None = None,
    sizes: Sizes | None = None,
) -> dict[str, Any]:
    seed = default_seed(run_date) if seed is None else seed
    sizes = sizes or Sizes()
    api = Api(api_base, api_fetch_json)
    datasets = [
        summarize(
            "equity_prices",
            "Preços de ações",
            PRICE_RULE,
            "B3, arquivo COTAHIST diário",
            check_equity_prices(api, fetch_bytes, seed, sizes.equity_prices, run_date),
        ),
        summarize(
            "corporate_events",
            "Proventos",
            DIVIDEND_RULE,
            "B3, GetListedCashDividends",
            check_corporate_events(api, b3_fetch_json, seed, sizes.corporate_events),
        ),
        summarize(
            "statements",
            "Demonstrações financeiras",
            STATEMENT_RULE,
            "CVM, DFP anual (dados abertos)",
            check_statements(api, fetch_bytes, seed, sizes.statements, run_date),
        ),
        summarize(
            "fund_quotas",
            "Cotas de fundos",
            QUOTA_RULE,
            "CVM, Informe Diário (dados abertos)",
            check_fund_quotas(api, fetch_bytes, seed, sizes.fund_quotas, run_date),
        ),
    ]
    empty = [d["dataset"] for d in datasets if d["compared"] == 0]
    if empty:
        # Nenhuma linha comparável: a fonte oficial inteira falhou. Uma rodada assim não
        # pode virar painel, então quem chama falha e tenta de novo depois.
        raise RuntimeError("fonte oficial sem nenhuma linha comparável: " + ", ".join(empty))
    return {
        "schema_version": SCHEMA_VERSION,
        "run_date": run_date.isoformat(),
        "seed": seed,
        "api_base": api_base,
        "sizes": asdict(sizes),
        "api_requests": api.calls,
        "datasets": datasets,
    }


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        prog="accuracy",
        description="Compara uma amostra da API pública da OBM com os arquivos oficiais.",
    )
    parser.add_argument("--api-base", default=os.environ.get("OBM_API_BASE", DEFAULT_API_BASE))
    parser.add_argument("--date", type=date.fromisoformat, default=date.today())
    parser.add_argument("--seed", type=int, default=None, help="padrão: a data como AAAAMMDD")
    parser.add_argument(
        "--sample-size",
        type=int,
        default=DEFAULT_SAMPLE_SIZE,
        metavar="N",
        help=(
            f"pontos por dataset (padrão {DEFAULT_SAMPLE_SIZE}, cerca de 60 chamadas à API, "
            "cabe no plano grátis de 10 por minuto e 200 por dia; 30 é a amostra cheia)"
        ),
    )
    parser.add_argument("--out", help="arquivo de saída (padrão: stdout)")
    args = parser.parse_args(argv)
    key = os.environ.get("OBM_API_KEY", "")
    if not key:
        print("Defina OBM_API_KEY com uma chave da API pública.", file=sys.stderr)
        return 2
    api_client = Client({"Authorization": f"Bearer {key}"})
    open_client = Client()
    result = run(
        api_base=args.api_base,
        api_fetch_json=api_client.get_json,
        fetch_bytes=open_client.get_bytes,
        b3_fetch_json=open_client.get_json,
        run_date=args.date,
        seed=args.seed,
        sizes=Sizes().limited(max(1, args.sample_size)),
    )
    text = json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
    if args.out:
        with open(args.out, "w", encoding="utf-8") as handle:
            handle.write(text)
    else:
        sys.stdout.write(text)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
