#!/usr/bin/python3
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#-*- coding: utf-8 -*-


# ##########################################################
"""
         FILE: supan
        USAGE: ./supan  
  DESCRIPTION: CLI to create SUSE-branded documents using pandoc
       AUTHOR: Raine Curtis (raine.curtis@suse.com) 
 ORGANIZATION: SUSE 
      CREATED: December 2, 2025
      UPDATED: December 8, 2025
"""
# ##########################################################
# Import necessary modules
import os
import sys
import subprocess
import argparse

sys.path.append("/usr/share/supan/lib")
import supanlib

# Global variables
VERSION="1.0"
DEFAULTS=".supan"
MODE=""
PRJPARENT="" 
PRJDIR=""
PRJTITLE="" 
PRJSUBTITLE="" 
PRJFILE=""
DOC=""
OUTDOC=""
AUTHOR=""
AUTHORTITLE=""
BUILD_MODES = ["new","pdf", "pdf-slides", "html", "docx", "odt", "pptx", "build-all" ]

# Term colors
RED = "\033[31m"
BOLD = "\033[1m"
SUSEJUNGLEGREEN = "\033[38;2;48;186;120m"
SUSEMINTGREEN = "\033[38;2;144;235;205m"
SUSEORANGE = "\033[38;2;250;124;63m"
SUSELIGHTBLUE = "\033[38;2;36;83;255m"
SUSEPURPLE = "\033[38;2;93;79;153m"
CLEAR= "\033[0m"

def chk_defaults():
    """
    Check for default author values
    """
    global AUTHOR, AUTHORTITLE
    home = os.path.expanduser("~")
    default_path = os.path.join(home, DEFAULTS)
    if os.path.isfile(default_path):
        [AUTHOR, AUTHORTITLE] = get_defaults()
    else:
        print(f"{BOLD}{SUSEORANGE}No default configuration file found at:{CLEAR} {default_path}")
        set_defaults(default_path)
        [AUTHOR, AUTHORTITLE] = get_defaults()

def get_defaults():
    """
    Get default values for author
    """
    global AUTHOR, AUTHORTITLE
    with open(os.path.join(os.path.expanduser("~"), DEFAULTS), 'r') as f:
        for line in f:
            if line.startswith("AUTHOR="):
                AUTHOR = line.strip().split('=', 1)[1]
            elif line.startswith("AUTHORTITLE="):
                AUTHORTITLE = line.strip().split('=', 1)[1]
    return AUTHOR, AUTHORTITLE

def set_defaults(default_path):
    """
    Set default values for author
    """
    global AUTHOR, AUTHORTITLE
    if not AUTHOR:
        default_author = "SUSE"
        default_title = "Global Services"
        AUTHOR = input(f"{SUSELIGHTBLUE}Enter a default document author [{default_author}]{CLEAR}: ") or default_author
    if not AUTHORTITLE:
        AUTHORTITLE = input(f"{SUSELIGHTBLUE}Enter a default author title [{default_title}]{CLEAR}: ") or default_title
    with open(default_path, 'w') as f:
        f.write(f"AUTHOR={AUTHOR}\n")
        f.write(f"AUTHORTITLE={AUTHORTITLE}\n")


def create_new_project():
    """
    Create a new SUSE-branded document project
    """
    global PRJPARENT, PRJDIR, PRJTITLE, PRJSUBTITLE, PRJFILE

    DEFAULT_PRJPARENT = os.getcwd()
    DEFAULT_PRJTITLE = "SUSE Document Project"
    DEFAULT_PRJSUBTITLE = "SUSE Document Subtitle"

    while True:
        PRJPARENT = input(f"{SUSEPURPLE}Enter project location [{DEFAULT_PRJPARENT}]: {CLEAR}") or DEFAULT_PRJPARENT

        if not os.path.isdir(PRJPARENT):
           print(f"{RED}Error: The specified location does not exist. Please try again.{CLEAR}")
           continue 

        PRJTITLE = input(f"{SUSEPURPLE}Enter document title [{DEFAULT_PRJTITLE}]: {CLEAR}") or DEFAULT_PRJTITLE
        PRJSUBTITLE = input(f"{SUSEPURPLE}Enter document subtitle [{DEFAULT_PRJSUBTITLE}]: {CLEAR}") or DEFAULT_PRJSUBTITLE
        PRJFILE = PRJTITLE.lower().replace(" ", "_") + ".md"
        print(f"{SUSELIGHTBLUE}Project Location:{CLEAR} {PRJPARENT}{CLEAR}")
        print(f"{SUSELIGHTBLUE}Project Title:{CLEAR} {PRJTITLE}{CLEAR}")
        print(f"{SUSELIGHTBLUE}Project Subtitle:{CLEAR} {PRJSUBTITLE}{CLEAR}")
        print(f"{SUSELIGHTBLUE}Project File:{CLEAR} {PRJFILE}{CLEAR}")  
        confirm = input(f"{SUSEPURPLE}Is this information correct? (y/n) {CLEAR}{SUSEORANGE}[y]: {CLEAR}") or "y"
        if confirm.lower() == 'y':
            break
        else:
            DEFAULT_PRJLOC = PRJPARENT
            DEFAULT_PRJTITLE = PRJTITLE
            DEFAULT_PRJSUBTITLE = PRJSUBTITLE

def set_md_file():
    """
    Set up the initial markdown file for the project
    """
    # Get a list of files in the project directory
    projfile = ""
    files = os.listdir(PRJDIR)
    mdfiles = []
    for file in files:
        filename, ext = os.path.splitext(file)
        if ext.lower() == '.md':
            mdfiles.append(file)
    if len(mdfiles) == 1:
        projfile = mdfiles[0]
        print(f"{SUSELIGHTBLUE}Using existing markdown file:{CLEAR} {projfile}{CLEAR}")
    elif len(mdfiles) > 1:
        while True:
            x = 1
            print(f"{SUSEORANGE}Found multiple markdown files in directory{CLEAR}")
            for md in mdfiles:
                print(f"{SUSELIGHTBLUE}{x}. {CLEAR} {md}{CLEAR}")
                x += 1
            choice = input(f"{SUSEPURPLE}Enter the markdown file to use for the document: {CLEAR}")
            if choice.isdigit() and 1 <= int(choice) <= len(mdfiles):
                projfile = mdfiles[int(choice) - 1]
                print(f"{SUSELIGHTBLUE}Using selected markdown file:{CLEAR} {projfile}{CLEAR}")
                break
    elif len(mdfiles) == 0:
        print(f"{BOLD}{RED}Error: No markdown files found in the project directory.{CLEAR}")
        quit()
    return projfile

# #######################################################
# Command-line start
# #######################################################
if __name__ == '__main__':
    print(f"{SUSEJUNGLEGREEN}SUSE Document Branding Utility (supan v. {VERSION}){CLEAR}")

    # Process command line arguments
    parser = argparse.ArgumentParser(
        description="Utility to create SUSE-branded documents using pandoc",
        prog="supan"
    )
    parser.add_argument('-e', '--examples',
                       choices=['true', 'false'],
                       help="Include example content in new project")
    parser.add_argument('-m', '--mode',
                       choices=BUILD_MODES,
                       help="Specify the operation mode")
    parser.add_argument('-a', '--standalone', 
                       choices=['true', 'false'],
                       help='Include standalone resources')
    parser.add_argument('-d', '--project_dir', 
                       help='Project directory location')
    args = parser.parse_args()

    if not args.mode:
        parser.print_help()
        quit()
    
    # Get default author values
    chk_defaults()
    print(f"{SUSEORANGE}Using Environment: {CLEAR}")
    print(f"{args}{CLEAR}")
    print(f"{SUSELIGHTBLUE}Author:{CLEAR} {AUTHOR}{CLEAR}")
    print(f"{SUSELIGHTBLUE}Author Title:{CLEAR} {AUTHORTITLE}{CLEAR}")

    # Execute based on mode
    # Create new project
    if args.mode == "new":
        print("Creating new SUSE-branded document project")
        create_new_project()
        print("Building project...")
        if args.examples:
            if args.examples == "True" or args.examples.lower() == 'true':
                examples_flag = True
        else:
            examples_flag = False

        if args.standalone:
            if args.standalone == "True" or args.standalone.lower() == 'true':
                standalone_flag = True
        else:
            standalone_flag = False

        result = supanlib.create_doc_project(PRJPARENT, PRJTITLE, 
                                    PRJSUBTITLE, PRJFILE, AUTHOR, AUTHORTITLE, 
                                    examples_flag, standalone_flag)
        if result:
            print(f"{SUSEJUNGLEGREEN}Project created successfully at:{CLEAR} {result}") 
        else:
            print(f"{RED}Failed to create project.{CLEAR}")
        quit()

    # Build document mode
    if args.mode in BUILD_MODES:
        if args.project_dir:
            PRJDIR= args.project_dir
        else:
            PRJDIR= os.getcwd()
        print(f"{SUSELIGHTBLUE}Project Directory: {CLEAR} {PRJDIR}{CLEAR}")
        PRJFILE = set_md_file()
        if args.mode == "build-all":
            modes_to_build = ["pdf", "pdf-slides", "html", "docx", "odt", "pptx"]
            for mode in modes_to_build:
                print(f"{SUSEORANGE}Building document in mode:{CLEAR} {mode}{CLEAR}")
                result = supanlib.build_doc(PRJDIR, PRJFILE, mode)
                if result:
                    print(f"{SUSEJUNGLEGREEN}Successfully built document:{CLEAR}{result}{CLEAR}\n")
                else:
                    print(f"{BOLD}{RED}Failed to build document in mode:{CLEAR} {mode}{CLEAR}\n")
        else:
            print(f"{SUSEORANGE}Building document in mode:{CLEAR} {args.mode}{CLEAR}")
            result = supanlib.build_doc(PRJDIR, PRJFILE, args.mode)
            if result:
                print(f"{SUSEJUNGLEGREEN}Successfully built document:{CLEAR}{result}{CLEAR}\n")
            else:
                print(f"{BOLD}{RED}Failed to build document.{CLEAR}")
