"""Build embed_page_fragment.html from lib/instance/templates/index.html."""
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / "lib" / "instance" / "templates" / "index.html"
OUT = ROOT / "lib" / "instance" / "templates" / "embed_page_fragment.html"

GRID_START = '    <div class="grid">'
STATS_START = '        <div class="card full stats-card'


def _slice_between(lines: list[str], start: str, end: str | None) -> list[str]:
    try:
        i = next(idx for idx, line in enumerate(lines) if line == start)
    except StopIteration:
        raise SystemExit(f"marker not found: {start!r}")
    if end is None:
        return lines[i:]
    try:
        j = next(idx for idx, line in enumerate(lines[i + 1 :], i + 1) if line.startswith(end))
    except StopIteration:
        raise SystemExit(f"end marker not found: {end!r}")
    return lines[i:j]


def main() -> None:
    lines = SRC.read_text(encoding="utf-8").splitlines()
    macro_start = next(i for i, l in enumerate(lines) if l.startswith("{% macro period_stats"))
    macro_end = next(i for i, l in enumerate(lines) if l.strip() == "{% endmacro %}")
    macro_body = lines[macro_start : macro_end + 1]

    grid_block = _slice_between(lines, GRID_START, STATS_START)
    # strip outer .grid wrapper; fragment adds its own
    if grid_block and grid_block[0] == GRID_START:
        grid_block = grid_block[1:]
    if grid_block and grid_block[-1].strip() == "</div>":
        # only remove closing div if it closes .grid (heuristic: last line before stats)
        pass

    stats_block = _slice_between(lines, STATS_START, "    </div>")

    out_lines = [
        "{# Hub iframe tab fragment — shared via embed_templates #}",
        *macro_body,
        '<div class="grid">',
        *grid_block,
        "</div>",
        *stats_block,
    ]
    text = "\n".join(out_lines).rstrip() + "\n"
    if "order_rule_tips_tpl" not in text:
        text = text.replace(
            "{% include 'order_monitor_rule_tips_binance.html' %}",
            "{% include order_rule_tips_tpl %}",
        )
    OUT.write_text(text, encoding="utf-8")
    print("wrote", OUT, "lines", len(out_lines))


if __name__ == "__main__":
    main()
