from app.lib.handwriting.aruco import rectify_page, rectify_page_color
from app.lib.handwriting.config import DEFAULT_MAX_IMG_WIDTH, DEFAULT_TEMPLATE_JSON
from app.lib.handwriting.font_build import build_ttf_with_fontforge
from app.lib.handwriting.glyphs import extract_glyphs, load_template
from app.lib.handwriting.grid import detect_grid_roi
from app.lib.handwriting.io_utils import (
    dump_image,
    ensure_dir,
    load_image,
    resize_if_needed,
    to_grayscale,
)
from app.lib.handwriting.vectorize import (
    clean_extracted_glyphs,
    vectorize_glyphs_with_potrace,
)


def run_pipeline(image_path, out_dir):
    ensure_dir(out_dir)

    frame = load_image(image_path)
    dump_image(out_dir, "a1_loaded.jpg", frame)

    frame = resize_if_needed(frame, DEFAULT_MAX_IMG_WIDTH)
    dump_image(out_dir, "a2_scaled.jpg", frame)

    gray = to_grayscale(frame)
    dump_image(out_dir, "a3_gray.jpg", gray)

    rectified = rectify_page(gray, out_dir)
    rectified_color = rectify_page_color(frame, out_dir)
    grid, grid_bbox = detect_grid_roi(rectified, out_dir)
    gx, gy, gw, gh = grid_bbox
    grid_color = rectified_color[gy : gy + gh, gx : gx + gw]

    template = load_template(DEFAULT_TEMPLATE_JSON)
    extract_glyphs(grid, template, out_dir, grid_color=grid_color)
    clean_extracted_glyphs(out_dir)
    vectorize_glyphs_with_potrace(out_dir)
    build_ttf_with_fontforge(out_dir)
    return grid
