import os
import yaml
from bs4 import BeautifulSoup

def adicionar_div_correcao(html_path):
    with open(html_path, 'r', encoding='utf-8') as file:
        soup = BeautifulSoup(file, 'html.parser')

        for div_tag in soup.find_all('div', class_='raw_html'):
            code_tag = div_tag.find('code')
            if code_tag:
                codigo = code_tag.decode_contents()
                nova_div = soup.new_tag('div', **{'class': 'correcao'})
                nova_div.append(BeautifulSoup(codigo, 'html.parser'))
                div_tag.replace_with(nova_div)

    with open(html_path, 'w', encoding='utf-8') as file:
        file.write(str(soup.prettify(formatter=None)))

def processar_htmls(diretorio):
    for root, dirs, files in os.walk(diretorio):
        for file_name in files:
            if file_name.endswith('.html'):
                html_path = os.path.join(root, file_name)
                adicionar_div_correcao(html_path)

def obter_output_dir_from_yaml():
    quarto_yaml_path = "_quarto.yml"
    with open(quarto_yaml_path, 'r', encoding='utf-8') as file:
        config = yaml.safe_load(file)
        return config['project']['output-dir']

if __name__ == "__main__":
    output_dir = obter_output_dir_from_yaml()
    pasta_htmls = os.path.join(os.path.dirname(__file__), output_dir)

    processar_htmls(pasta_htmls)
