import os
import re
import glob
import shutil
import subprocess
import markdown
import yaml
import pydantic
from typing import Optional
from datetime import datetime, date
from dotmap import DotMap

from .common import filepath_or_string, GlobalVars, SiteConfig
from .templating import format_html_template, map_templates
from .assets import pull_git_repo, copy_assets
from .articles import ArticleMetadata, load_markdown, build_articles, build_index









def build_site(site: SiteConfig, templates: DotMap):

    # Initialize the build cache and web root, in case they do not exist.
    os.makedirs(site.build_cache, exist_ok = True)
    os.makedirs(site.web_root, exist_ok = True)

    # If the site is built from a git repo, pull that repo into the build cache.
    if site.git_repo:
        pull_git_repo(site.git_repo, site.build_cache)

    # Copy the sites assets into the web root.
    copy_assets(site)

    # Load the site's articles into an index.
    index = build_index(site)

    # Generate HTML pages for the articles.
    build_articles(site, index, templates)


def main():
    with open('/home/jim/projects/shepich.com/config.yaml', 'r') as config_file:
        config = yaml.safe_load(config_file.read())
    
    templates = map_templates(config['templates_folder'])

    for site in config['sites'].values():
        build_site(SiteConfig(**site), templates)
    

if __name__ == '__main__':
   main()

