#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import argparse
import pprint

from embellish import engine, server

usage = '''
===================================================
EMBELLISH: a low friction static website generator.
=================================================== 
Looks for markdown files (*markdown, *mkd, *md, *txt) and
converts them into HTML pages using HAML/jinja2
templates (*haml) with a little SASS and HAML processing.
'''

print(usage)
parser = argparse.ArgumentParser()
parser.add_argument(
  'target', 
  help='web directory of source and output, or a site.yaml configuration file')
parser.add_argument(
  '--monitor', '-m', action="store_true",
  help='triggers a local web-server that monitors the'
  ' contents directory')
args = parser.parse_args()

if os.path.isfile(args.target):
  site = engine.read_config_yaml(args.target)
  config_dir = os.path.dirname(args.target)
elif os.path.isdir(args.target):
  os.chdir(args.target)
  site = engine.default_site
  config_dir = args.target
else:
  print('Error: can\'t figure out {0}.'.format(args.target))
  sys.exit(1)

engine.generate_site_incrementally(site)

if args.monitor:
  site_dir = os.path.abspath(
      os.path.join(config_dir, site['output_dir']))
  # normalize all paths
  for key in site.keys():
    if key.endswith('_dir') or key.startswith('cache'):
      site[key] = os.path.abspath(os.path.join(site_dir, site[key]))

  regenerate = lambda: engine.generate_site_incrementally(site)

  # get all directories needed to monitor
  keys = ['content_dir', 'template_dir', 'media_dir']
  monitor_dirs = [site[key] for key in keys]

  server.run(site_dir, monitor_dirs, regenerate)


