# Copyright (C) 2007-2026 Ahmet Öztürk (aoz_2@yahoo.com)
#
# This file is part of Lifeograph.
#
# Lifeograph is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Lifeograph is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Lifeograph.  If not, see <http://www.gnu.org/licenses/>.

from LoG import *
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

NAME="Render Math Formula (Experimental)"
VERSION="0.1"
CATEGORY=SCtg.WORD_MODIFIER

def run(para: Paragraph, pos_bgn, pos_end):
    img_uri = _render_formula_for_para(para)
    para.set_uri(img_uri)
    para.set_image_type(VT.PS.IMAGE_FILE)
    para.set_image_size(0) # minimum
    para.set_alignment(VT.PS.ALIGN_C)
    para.add_format(VT.FMT.FADED)
    refresh_panels()

def _render_formula_for_para(para) -> str:
    formula = para.get_text().strip()
    para_id = para.get_id()

    base_dir = Path(Diary.get_main().get_rel_folder_path())
    formulas_dir = base_dir / "formulas"
    formulas_dir.mkdir(parents=True, exist_ok=True)
    filename = f"{para_id}.png"

    out_path = formulas_dir / filename
    img_rel_uri = (
        "rel://" +
        Diary.get_main().get_rel_folder_name() +
        "/formulas/" +
        filename )

    fig = plt.figure(figsize=(0.01, 0.01))
    fig.patch.set_alpha(0)

    plt.text(
        0.5, 0.5,
        f"${formula}$",
        fontsize=18,
        ha="center",
        va="center"
    )

    plt.axis("off")

    plt.savefig(
        out_path,
        format="png",
        dpi=300,
        bbox_inches="tight",
        pad_inches=0.05
    )
    plt.close(fig)

    return img_rel_uri
