#!/usr/bin/env python
""" Build working copies of nobel_prize paper
"""

import os
from os.path import (dirname, abspath, join as pjoin, isdir)
import re
import shutil
import zipfile

MY_PATH = abspath(dirname(__file__))
OUT_PATH = abspath(pjoin(MY_PATH, '..', 'np-versions'))
VER_RE = re.compile(r"^(.*?)\.v(\d+.*?)$")
ANA_SCRIPT = 'clever_analysis.py'
EXPENSIVE_DATA = 'expensive_data.csv'


def sort_into_versions(path):
    versions = {}
    for sub_path in os.listdir(path):
        ver_match = VER_RE.match(sub_path)
        if ver_match is None:
            continue
        fname, ver = ver_match.groups()
        if ver not in versions:
            versions[ver] = []
        versions[ver].append((pjoin(path, sub_path), fname))
    return versions


def exec_file(path, cwd):
    old_cwd = os.getcwd()
    try:
        os.chdir(cwd)
        with open(path, 'rt') as fobj:
            exec(fobj.read(), {})
    finally:
        os.chdir(old_cwd)


if isdir(OUT_PATH):
    shutil.rmtree(OUT_PATH)
os.makedirs(OUT_PATH)

VER_FILES = sort_into_versions(MY_PATH)

first_work = True
for version in sorted(VER_FILES):
    work_dir = pjoin(OUT_PATH, 'work' + version)
    os.makedirs(work_dir)
    expensive_path = pjoin(work_dir, EXPENSIVE_DATA)
    if first_work:
        exec_file(pjoin(MY_PATH, 'make_expensive_data.py'), work_dir)
        expensive_stored = expensive_path
    for in_path, out_fname in VER_FILES[version]:
        shutil.copy(in_path, pjoin(work_dir, out_fname))
        if not out_fname == ANA_SCRIPT:
            continue
        mplrc = pjoin(work_dir, 'matplotlibrc')
        if not first_work:
            shutil.copy(expensive_stored, expensive_path)
        with open(mplrc, 'wt') as fobj:
            fobj.write("backend : agg")
        exec_file(ANA_SCRIPT, work_dir)
        os.unlink(mplrc)
        if not first_work:
            os.unlink(expensive_path)
    first_work = False

# Build nobel_prize.zip archive
WORK1 = pjoin(OUT_PATH, 'work1')
os.chdir(OUT_PATH)
shutil.copytree(WORK1, 'nobel_prize')
z = zipfile.ZipFile('nobel_prize.zip', 'w')
for path in os.listdir('nobel_prize'):
    fname = pjoin('nobel_prize', path)
    z.write(fname, fname)
z.close()
shutil.rmtree('nobel_prize')

with open('README.rst', 'wt') as fobj:
    fobj.write(
"""np-versions
===========

Autogenerated by ``np-tools/build_np_versions.py``.

Do not edit
""")
