<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def finalize(doc):
 """Adds the pgfplots and caption packages to the header-includes if needed. """

    if doc.plot_found:
        pgfplots_inline = pf.MetaInlines(pf.RawInline(
            r'''%
\makeatletter
\@ifpackageloaded{pgfplots}{}{\usepackage{pgfplots}}
\makeatother
\usepgfplotslibrary{groupplots}
''', format='tex'))
        try:
            doc.metadata['header-includes'].append(pgfplots_inline)
        except KeyError:
            doc.metadata['header-includes'] = pf.MetaList(pgfplots_inline)

    if doc.caption_found:
        caption_inline = pf.MetaInlines(pf.RawInline(
            r'''%
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\@ifpackageloaded{cleveref}{}{\usepackage{cleveref}}
\@ifundefined{codelisting}{%
    \DeclareCaptionType{codelisting}[Code Listing][List of Code Listings]
    \crefname{codelisting}{code listing}{code listings}
    \Crefname{codelisting}{Code Listing}{Code Listings}
    \captionsetup[codelisting]{position=bottom}
}{}
\makeatother
''', format='tex'))
        try:
            doc.metadata['header-includes'].append(caption_inline)
        except KeyError:
            doc.metadata['header-includes'] = pf.MetaList(caption_inline)