# readme_helper.py
# Utility for reading README files and providing help text for CLI scripts.

import os

# Supported README file extensions in order of preference
README_EXTENSIONS = [".md", ".txt"]


def read_readme_as_help(script_file, readme_filename=None):
    """
    Read a README file from the same directory as a script and return its contents.
    
    Intended for use with argparse epilog to provide extended help text.
    Supports both .txt and .md files. If no filename is specified, auto-detects
    README.md or README.txt (in that order).
    
    Args:
        script_file: The __file__ of the calling script (used to locate the README).
        readme_filename: Name of the README file, or None to auto-detect.
    
    Returns:
        String containing the README contents, or a fallback message if not found.
    
    Example usage:
        parser = argparse.ArgumentParser(
            description="My Script Description",
            epilog=read_readme_as_help(__file__),
            formatter_class=argparse.RawDescriptionHelpFormatter
        )
    """
    script_dir = os.path.dirname(os.path.abspath(script_file))
    
    # Find the README file
    readme_path = None
    found_filename = None
    
    if readme_filename:
        # Specific filename provided
        path = os.path.join(script_dir, readme_filename)
        if os.path.exists(path):
            readme_path = path
            found_filename = readme_filename
    else:
        # Auto-detect: try each extension in order of preference
        for ext in README_EXTENSIONS:
            filename = "README" + ext
            path = os.path.join(script_dir, filename)
            if os.path.exists(path):
                readme_path = path
                found_filename = filename
                break
    
    if readme_path is None:
        search_name = readme_filename if readme_filename else "README.md or README.txt"
        return "\nCould not find %s. Please refer to it for further instructions." % search_name
    
    try:
        with open(readme_path, 'r', encoding='utf-8') as f:
            content = f.read()
    except IOError:
        return "\nCould not read %s." % found_filename
    
    # Add a header to indicate this is from the README
    lines = [
        "",
        "=" * 70,
        "From %s:" % found_filename,
        "=" * 70,
        "",
        content.strip()
    ]
    
    return '\n'.join(lines)
