package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/yuin/goldmark/ast"
)

func main() {
	inputMd := flag.String("i", "report.md", "Input Markdown file")
	outputPdf := flag.String("o", "projektarbeit.pdf", "Output PDF file")
	kroki := flag.String("kroki", "https://kroki.io", "Kroki base URL (e.g. http://localhost:8000 for a local instance)")
	flag.Parse()

	krokiBaseURL = *kroki

	config, doc, content, err := ParseMarkdown(*inputMd)
	if err != nil {
		log.Fatalf("Failed to parse input: %v", err)
	}

	// Pass 1 — dummy render to collect page numbers for the TOC, tables, and figures.
	// The recorded page numbers are used to fill the TOC in pass 2.
	pass1 := NewIHKRenderer(config)
	if err = renderPipeline(pass1, doc, content); err != nil {
		log.Fatalf("Pass 1 failed: %v", err)
	}

	// Pass 2 — final render with the TOC index collected in pass 1.
	// Only tocItems must be pre-seeded because RenderTOC() runs before RenderAST().
	// tableItems and figureItems are re-populated during RenderAST() in pass 2,
	// so they must NOT be copied here (that would produce duplicates in the lists).
	pass2 := NewIHKRenderer(config)
	pass2.tocItems = pass1.tocItems
	if err = renderPipeline(pass2, doc, content); err != nil {
		log.Fatalf("Pass 2 failed: %v", err)
	}

	if err = pass2.Save(*outputPdf); err != nil {
		log.Fatalf("Failed to save PDF: %v", err)
	}
	fmt.Printf("PDF created: %s\n", *outputPdf)
}

// renderPipeline executes the full document rendering sequence in the mandatory
// IHK Chemnitz order:
//
//  1. Title page         (no page number)
//  2. Table of contents  (Roman II)
//  3. List of abbrev.    (Roman, from YAML — optional)
//  4. Body via AST walk  (foreword Roman → main body Arabic from 1)
//  5. Bibliography       (Arabic, A–Z sorted)
//  6. List of tables     (Arabic)
//  7. List of figures    (Arabic)
//  8. Appendix / annex   (Arabic)
//  9. Glossary           (Arabic, from YAML — optional)
//  10. Declaration       (no page number)
func renderPipeline(r *IHKRenderer, doc ast.Node, content []byte) error {
	r.RenderTitlePage()
	r.RenderTOC()
	r.RenderAbbreviations()

	if err := RenderAST(doc, content, r); err != nil {
		return err
	}

	r.RenderBibliography()
	r.RenderListOfTables()
	r.RenderListOfFigures()
	r.RenderAppendices()
	r.RenderGlossary()
	r.RenderDeclarationPage()
	return nil
}
