"""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\">"


def _find_line(lines: list[str], predicate, *, start: int = 0) -> int:
    for idx in range(start, len(lines)):
        if predicate(lines[idx]):
            return idx
    raise SystemExit("marker not found")


def main() -> None:
    lines = SRC.read_text(encoding="utf-8").splitlines()
    macro_start = _find_line(lines, lambda l: "macro period_stats_pane" in l)
    macro_end = _find_line(lines, lambda l: l.strip() == "{% endmacro %}", start=macro_start)
    macro_body = lines[macro_start : macro_end + 1]

    grid_start = _find_line(lines, lambda l: l == GRID_START)
    panel_start = _find_line(
        lines, lambda l: l.strip() == "{% if page == 'env_config' %}"
    )
    stats_card_line = _find_line(lines, lambda l: 'id="stats-card"' in l)
    stats_start = stats_card_line
    while stats_start > 0 and lines[stats_start].strip() != "{% if page == 'stats' %}":
        stats_start -= 1
    if lines[stats_start].strip() != "{% if page == 'stats' %}":
        raise SystemExit("stats if-block not found")
    stats_end = _find_line(lines, lambda l: l.strip() == "{% endif %}", start=stats_start + 1)

    grid_block = lines[grid_start + 1 : panel_start]
    while grid_block and not grid_block[-1].strip():
        grid_block.pop()
    if grid_block and grid_block[-1].strip() == "</div>":
        grid_block.pop()

    panel_block = lines[panel_start:stats_start]
    stats_block = lines[stats_start : stats_end + 1]

    out_lines = [
        "{# Hub iframe tab fragment — shared via embed_templates #}",
        *macro_body,
        '<div class="grid">',
        *grid_block,
        "</div>",
        *panel_block,
        *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()
