#!/usr/bin/env python3
"""
Week 2 Lab 2.2 – Cookiecutter Project Template (Python Version)
Author: Kwabena Nketia
Date: 2026-02-03
"""

import os
from pathlib import Path
import json
import subprocess
import tkinter as tk
from tkinter import filedialog

# # 1. Define Project Root - Option 1, hard code path
# proj_root = Path("/Lab/week_2")


# 1. Define Project Root - Option 2, automate the root path

root = tk.Tk()
root.withdraw()

proj_root_path = filedialog.askdirectory(title="Select the Project Root Folder")
if not proj_root_path:
    raise SystemExit("No folder selected. Exiting.")

proj_root = Path(proj_root_path)
print(f"Project root folder selected: {proj_root}")

# Cookiecutter template folder
cc_root_folder = proj_root / "cookiecutter-ag-data-management"
cc_root_folder.mkdir(parents=True, exist_ok=True)
print(f"Template folder created at: {cc_root_folder}")


# 2. Create cookiecutter.json

cookiecutter_config = {
    "project_name": "Agricultural Data Management Project",
    "project_slug": "ag-data-project",
    "author_name": "Your Name",
    "institution": "University of Saskatchewan",
    "year": "2026",
    "license": "CC-BY-4.0"
}

json_path = cc_root_folder / "cookiecutter.json"
with open(json_path, "w") as f:
    json.dump(cookiecutter_config, f, indent=4)
print(f"cookiecutter.json created at: {json_path}")


# 3. Create Template Project Folder

template_project_path = cc_root_folder / "{{cookiecutter.project_slug}}"
template_project_path.mkdir(parents=True, exist_ok=True)
print(f"Template project folder created at: {template_project_path}")


# 4. Create Standard Folders

folders = [
    "data_raw",
    "data_clean",
    "metadata",
    "scripts/data_cleaning",
    "scripts/analysis",
    "scripts/spatial",
    "scripts/utils",
    "analysis/exploratory",
    "analysis/statistical",
    "analysis/spatial",
    "analysis/reports",
    "outputs/tables",
    "outputs/figures",
    "outputs/maps",
    "outputs/models",
    "publishing",
    "docs"
]

for folder in folders:
    path = template_project_path / folder
    path.mkdir(parents=True, exist_ok=True)
print("Template folder structure created successfully!")


# 5. Create README.md

readme_content = """
# {{cookiecutter.project_name}}

**Author:** {{cookiecutter.author_name}}  
**Institution:** {{cookiecutter.institution}}  
**Year:** {{cookiecutter.year}}

## Project Description
This repository contains agricultural data and analysis organized using
reproducible data management best practices.

## Folder Structure
- data_raw/        – Original unmodified data
- data_clean/      – Cleaned, analysis-ready data
- metadata/        – Documentation and metadata
- scripts/         – Reusable code
- analysis/        – Analytical workflows
- outputs/         – Generated results
- publishing/      – Repository-ready datasets
- docs/            – Supporting documentation

## License
This dataset is released under the {{cookiecutter.license}} license.
"""

readme_path = template_project_path / "README.md"
with open(readme_path, "w") as f:
    f.write(readme_content)
print("README.md template created successfully!")


# 6. Run Cookiecutter to Generate Project

try:
    subprocess.run(["cookiecutter", str(cc_root_folder)], check=True)
    print("Cookiecutter project generation complete!")
except subprocess.CalledProcessError:
    print("Error: Cookiecutter failed. Make sure it is installed and on your PATH.")


# # 6b. Non-interactive Cookiecutter
# defaults = {
#     "project_name": "Agricultural Data Management Project",
#     "project_slug": "ag-data-project",
#     "author_name": "Kwabena Nketia",
#     "institution": "University of Saskatchewan",
#     "year": "2026",
#     "license": "CC-BY-4.0"
# }
# 
# subprocess.run([
#     "cookiecutter",
#     str(cc_root_folder),
#     "--no-input",
#     f'project_name={defaults["project_name"]}',
#     f'project_slug={defaults["project_slug"]}',
#     f'author_name={defaults["author_name"]}',
#     f'institution={defaults["institution"]}',
#     f'year={defaults["year"]}',
#     f'license={defaults["license"]}'
# ], check=True)
# 
# print("Cookiecutter project generated non-interactively!")


## EOF
