import os
from datetime import datetime
from pathlib import Path
import subprocess
from git.utils import init_git_user
from actions_logging.app_logging import logger


def get_summary(readme_path):
    logger.debug(f"Retrieving summary from {readme_path}")
    if readme_path.exists():
        with open(readme_path, 'r', encoding='utf-8') as file:
            l = file.readline().strip()
            if l.startswith("##"):
                summary = l[2:].strip()
                return summary
            else:
                return l
    else:
        logger.warning(f"README file not found at {readme_path}")
    return "<span style='color:gray;'><i>No summary available.</i></span>"

def get_last_updated(path):
    try:
        timestamp = os.path.getmtime(path)
        formatted_time = datetime.fromtimestamp(timestamp).strftime('%m/%d/%Y')
        logger.debug(f"Last updated time for {path} is {formatted_time}")
        return formatted_time
    except OSError as e:
        logger.error(f"Error retrieving modification time for {path}: {e}")
        return "Unknown date"

def process_directory(directory):
    logger.debug(f"Processing directory: {directory}")
    logger.debug(f"Current directory: {os.getcwd()}")
    logger.debug(f"List DIR . {os.listdir('.')}")
    summaries = {}
    try:
        directories = os.listdir(directory)
        logger.debug(f"Directories found in {directory}: {directories}")
        for item in sorted(directories):
            path = os.path.join(directory, item)
            if os.path.isdir(path):
                readme_path = Path(path) / 'README.md'
                summary = get_summary(readme_path)
                last_updated = get_last_updated(path)
                subfolder_summaries = process_directory(path)
                summaries[item] = {"summary": summary, "path": str(readme_path), "last_updated": last_updated,
                                   "subfolders": subfolder_summaries}
        return summaries
    except Exception as e:
        logger.error(f"An error occurred while processing directory {directory}: {e}")
        return summaries

def create_super_readme2(summaries, root_path):
    super_readme_path = os.path.join(root_path, 'SUPER_README.md')
    try:
        logger.debug(f"Writing to SUPER_README.md at {super_readme_path}")
        with open(super_readme_path, 'w', encoding='utf-8') as file:
            file.write(f"<h1 style='color:blue;'>💾️ Overview of Project: {Path(root_path).name}</h1>\n\n")
            file.write(f"<h2>Legend</h2>\n")
            file.write(f"<ul>\n")
            file.write(
                f"  <li><span style='color:green;'>📂</span> - Main action folders: These folders contain key actions "
                f"and processes central to the project's functionality.</li>\n")
            file.write(
                f"  <li><span style='color:darkorange;'>📑</span> - Action subfolders: These are sub-directories "
                f"under the main action folders, detailing specific actions or smaller tasks.</li>\n")
            file.write(
                f"  <li><span style='color:gray;'>Gray</span> - Summary text: General descriptions or summaries found "
                f"within each folder.</li>\n")
            file.write(f"</ul>\n\n")

            for main_folder, content in summaries.items():
                file.write(f"<h2 style='color:green;'>📂 <b>{main_folder}</b></h2>\n\n")
                write_summaries(content, file, level=2)
                file.write("\n")
    except Exception as e:
        logger.error(f"Failed to create or write to SUPER_README.md at {root_path}: {e}")

def create_super_readme(summaries, root_path):
    logger.debug(f"Creating SUPER_README for {root_path}")
    # Correct the path if the root_path incorrectly includes the 'actions' directory twice
    if root_path.endswith('actions'):
        super_readme_path = os.path.join(os.path.abspath(root_path), "SUPER_README.md")
    else:
        super_readme_path = os.path.join(os.path.abspath(root_path), "actions", "SUPER_README.md")

    # Ensure the directory exists before trying to write the file
    os.makedirs(os.path.dirname(super_readme_path), exist_ok=True)

    try:
        logger.debug(f"Writing to SUPER_README.md at {super_readme_path}")
        with open(super_readme_path, 'w', encoding='utf-8') as file:
            file.write(f"<h1 style='color:blue;'>💾️ Overview of Project: {Path(root_path).name}</h1>\n\n")
            file.write(f"<h2>Legend</h2>\n")
            file.write(f"<ul>\n")
            file.write(
                f"  <li><span style='color:green;'>📂</span> - Main action folders: These folders contain key actions "
                f"and processes central to the project's functionality.</li>\n")
            file.write(
                f"  <li><span style='color:darkorange;'>📑</span> - Action subfolders: These are sub-directories "
                f"under the main action folders, detailing specific actions or smaller tasks.</li>\n")
            file.write(
                f"  <li><span style='color:gray;'>Gray</span> - Summary text: General descriptions or summaries found "
                f"within each folder.</li>\n")
            file.write(f"</ul>\n\n")

            for main_folder, content in summaries.items():
                file.write(f"<h2 style='color:green;'>📂 <b>{main_folder}</b></h2>\n\n")
                write_summaries(content, file, level=2)
                file.write("\n")
        pass
    except Exception as e:
        logger.error(f"Failed to create or write to SUPER_README.md at {root_path}: {e}")
        raise

def write_summaries(content, file, level):
    if content['subfolders']:
        for subfolder, info in content['subfolders'].items():
            file.write(
                f"- <h4 style='color:darkorange;'>📑 {subfolder}</h4> <span style='color:gray; font-size:0.9em;'>{info['summary']}</span>\n")
            file.write(
                f"  <span style='color:lightgray; font-size:0.8em;'>Last updated: {info['last_updated']}</span>\n\n")
            file.write(f"  <span style='color:darkgray; font-size:0.6em;'>Path: {info['path']}</span>\n")
            if info['subfolders']:
                write_summaries(info, file, level + 1)


def git_add(file_path):
    try:
        subprocess.run(["git", "add", file_path], check=True)
        logger.debug(f"Successfully added {file_path} to staging area.")
    except subprocess.CalledProcessError as e:
        logger.error(f"Failed to add {file_path} to staging area: {e}")
        if e.returncode == 128:
            logger.error("This may indicate the directory is not a git repository or the file path is incorrect.")
        else:
            logger.error(f"Git add failed with error code {e.returncode}")
    except Exception as e:
        logger.error(f"An unexpected error occurred while adding files to Git: {str(e)}")


def git_push():
    logger.debug("Initializing git user and attempting to push changes")
    init_git_user()
    try:
        subprocess.run(["git", "pull"], check=True)  # Pull before pushing to avoid conflicts
        git_add('actions/SUPER_README.md')
        subprocess.run(["git", "commit", "-m", "Update SUPER_README.md"], check=True)
        subprocess.run(["git", "push", "origin", "main"], check=True)
        logger.debug("Git push was successful.")
    except subprocess.CalledProcessError as e:
        logger.error(f"Failed to push changes to the remote repository: {e}")
        if e.returncode == 128:
            logger.error("This might be a credential or SSH key issue, or conflicts needing manual resolution.")
        else:
            logger.error(f"Git push failed with error code {e.returncode}")
    except Exception as e:
        logger.error(f"An unexpected error occurred during Git operations: {str(e)}")



def main():
    ROOT_FOLDER_PATH = os.getenv("ROOT_FOLDER_PATH", "actions")
    root_directory = ROOT_FOLDER_PATH
    logger.info(f"Starting 'redmefying' on root directory: {os.path.abspath(root_directory)}")
    summaries = process_directory(root_directory)
    create_super_readme(summaries, root_directory)
    git_push()

if __name__ == "__main__":
    main()
