#!/usr/bin/env python3
# create - creates an empty post to fill in
import getopt
import argparse
import sys
import datetime
import re
import os
import os.path
import shutil
from collections import defaultdict

# options are: t for tags, a for author, i for image
# tags are comma-separated
# author is any string
# image is an image file. if it exists, it is moved to the post image directory with the name adjusted

p = argparse.ArgumentParser()
p.add_argument("-t", "--tags", nargs='*', action='append', default=[])
p.add_argument("-c", "--categories", nargs="*", action='append', default=[])
p.add_argument("-a", "--author", default=os.getlogin())
p.add_argument("-d", "--date", default=datetime.date.today().isoformat())
p.add_argument("-i", "--image")
p.add_argument("-l", "--language", default="")
p.add_argument("title", nargs="+")
o = p.parse_args()

tags = '"' + '","'.join(sum(o.tags, [])) + '"'
cats = '"' + '","'.join(sum(o.categories, [])) + '"'
date = o.date
title = " ".join(o.title)
value = re.sub(r'[^\w\s-]', '', title.lower())
filetitle = date + "-" + re.sub(r'[-\s]+', '-', value).strip('-_')
lang = ""
if o.language != "":
  lang = f".{o.language}"
filename = 'content/post/' + filetitle + lang + '.md'
author = o.author
image = o.image if o.image else ""
#print(f"{tags=} {cats=} {date=} {title=} {filetitle=} {author=} {image=}")
destimage = ""
if os.path.exists(image):
  print(image, "exists")
  ext = os.path.splitext(image)[1]
  yearmont = date[0:4] + '/' + date[5:7]
  destimage = f'{yearmont}/{filetitle}{ext}'
  destdir = f'./static/{yearmont}/'
  dest = f'{destdir}{filetitle}{ext}'
  if not os.path.exists(destdir):
    os.makedirs(destdir)
  print("destination", dest)
  shutil.copy2(image, dest)
  print('copy2', image, f'{dest}')


if os.path.exists(filename):
  print(f"File {filename} already exists")
  exit(1)

print(f"Writing to {filename}")
with open(filename, 'w') as f:
  f.write('---\n')
  f.write(f'title: "{title}"\n')
  f.write(f'date: "{date}"\n')
  if author == "":
    f.write(f'#author: ""\n')
  else:
    f.write(f'author: "{author}"\n')
  f.write(f'tags: [{tags}]\n')
  f.write(f'categories: [{cats}]\n')
  f.write(f'featuredImage: "{destimage}"\n')
  f.write(f"#attribution: '{destimage}'\n")
  f.write(f'#summary: ""\n')
  f.write(f'#series: [""]: \n')
  f.write(f'#excludeFromIndex: true\n')
  f.write(f'featured: true\n')
  f.write(f'draft: true\n')
  f.write('---\n')
  f.write('\n')
