"""Dựng nến M15/H1/H4 từ tick canonical vào thư mục NGOÀI data/ (scratch), dùng BarBuilder.ticks_to_bars (khớp byte với data/bars
trên ngày mẫu 2023-06-14). Không áp luật loại ngày. Dùng cho các lượt thăm dò 2026-09-18.
Usage (repo root): .venv/bin/python <this> <source: exness|dukascopy_csv> <from 'year=YYYY/month=MM'> <to-exclusive 'year=YYYY'> <out_dir> <tag>
  exness:        exness year=2023/month=07 year=2027 <scratch> 2023H2_2026   → bars_{TF}_2023H2_2026.parquet
  dukascopy_csv: dukascopy_csv year=2004/month=07 year=2024 <scratch> 2004H2_2023 → duka_{TF}_2004H2_2023.parquet"""
import sys, pathlib
import polars as pl
from xau_lab.data.bars import BarBuilder
src, lo, hi, outd, tag = sys.argv[1:6]
root = pathlib.Path(f"data/canonical/source={src}/symbol=XAUUSD"); bb = BarBuilder(base_dir=pathlib.Path("."))
fs = [f for f in sorted(root.glob("year=*/month=*/day=*/ticks.parquet")) if lo <= str(f.relative_to(root))[:len(lo)] and str(f.relative_to(root)) < hi]
out = {k: [] for k in ("M15", "H1", "H4")}
for f in fs:
    t = pl.read_parquet(f)
    for k in out: out[k].append(bb.ticks_to_bars(t, k).with_columns(pl.col("timestamp_utc").dt.cast_time_unit("us")))
prefix = "bars" if src == "exness" else "duka"
for k, v in out.items():
    pl.concat(v).sort("timestamp_utc").write_parquet(pathlib.Path(outd) / f"{prefix}_{k}_{tag}.parquet")
print(len(fs), "ngày")
