import sys, json, shutil, contextlib, io
sys.path.insert(0,".")
from pathlib import Path
import smart_extractor as se
from _lines import separator_barriers
base=Path("output/AndhraJyothi_Siddipet District_20260602_20260603_144919")
D=base/"pages"; out=base/"pg2_all_current"
if out.exists(): shutil.rmtree(out)
png=D/"page_002.png"
regs=json.loads((D/"page_002.regions.json").read_text())["regions"]
with contextlib.redirect_stdout(io.StringIO()):
    regs=se.drop_masthead_regions(regs,"andhra_jyothi",2,png)
    ds=se.find_article_starts_by_dateline(regs,str(png),"andhra_jyothi")
    bars=separator_barriers(str(png),regs)
    bl=se.cluster_all_article_blocks(regs,dateline_starts=ds,sep_lines=bars)
    n=se.crop_all_article_blocks(str(png),regs,str(out),2,dateline_starts=ds,sep_lines=bars)
for b in sorted(bl,key=lambda d:(d["bbox"][1],d["bbox"][0])):
    print(f"{b['kind']:>2} anchor={b['anchor_id']:>3} bbox={b['bbox']} w={b['bbox'][2]-b['bbox'][0]}")
print(f"\n{n} crops -> {out}/page_002/")
