import argparse
import os
import sys
import ssl
from rich.console import Console
from rich.markdown import Markdown
from tmd.renderer import POSMarkdown

def setup_nltk_ssl():
    """
    patch ssl context to allow unverified https requests for nltk downloaders.
    this fixes issues on some corporate networks or macos python installations.
    """
    try:
        _create_unverified_https_context = ssl._create_unverified_context
    except AttributeError:
        pass
    else:
        ssl._create_default_https_context = _create_unverified_https_context

def ensure_nltk_data():
    """
    check and download necessary nltk data packages.
    returns true if all data is available, false otherwise.
    """
    import nltk
    
    required_packages = ['punkt', 'averaged_perceptron_tagger', 'punkt_tab', 'averaged_perceptron_tagger_eng']
    console = Console()
    
    # attempt to fix ssl issues before downloading
    setup_nltk_ssl()
    
    missing_packages = []
    for package in required_packages:
        try:
            nltk.data.find(f'tokenizers/{package}')
        except LookupError:
            try:
                 nltk.data.find(f'help/{package}') 
            except LookupError:
                try:
                    nltk.data.find(f'taggers/{package}')
                except LookupError:
                    # specific check for pickle files
                    if 'averaged_perceptron_tagger' in package:
                        try:
                            nltk.data.find(f'taggers/{package}.pickle')
                        except LookupError:
                            missing_packages.append(package)
                            continue
                    else:
                        missing_packages.append(package)

    if not missing_packages:
        return True

    console.print(f"[dim]initializing nlp resources (downloading {len(missing_packages)} packages)...[/dim]")
    
    try:
        for package in missing_packages:
            nltk.download(package, quiet=True)
        return True
    except Exception as e:
        console.print(f"[yellow]warning: failed to download nlp data. pos tagging will be disabled.[/yellow]")
        console.print(f"[dim]error details: {e}[/dim]")
        return False

def render_markdown(file_path, enable_pos=True):
    # check if file exists
    if not os.path.exists(file_path):
        print(f"error: file '{file_path}' does not exist.")
        return

    if not os.path.isfile(file_path):
        print(f"error: '{file_path}' is not a valid file.")
        return

    console = Console()

    try:
        with open(file_path, "r", encoding="utf-8") as file:
            content = file.read()
    except Exception as e:
        print(f"error: could not read file: {e}")
        return

    if not content:
        print(f"warning: file '{file_path}' is empty.")
        return

    # logic to safely enable pos tagging
    final_md_class = Markdown
    
    if enable_pos:
        try:
            # check if nltk is actually importable (handles rare broken installs)
            import nltk
            if ensure_nltk_data():
                final_md_class = POSMarkdown
            else:
                # fallback if data download failed
                final_md_class = Markdown
        except ImportError:
            console.print("[yellow]warning: nltk library not found. falling back to standard rendering.[/yellow]")
            final_md_class = Markdown
        except Exception as e:
            console.print(f"[yellow]warning: unexpected error initializing nlp engine: {e}. falling back.[/yellow]")
            final_md_class = Markdown

    md = final_md_class(content)
    console.print(md)

def main():
    parser = argparse.ArgumentParser(
        description="terminal-markdown (tmd): A CLI tool to render markdown files with POS tagging. | 终端 Markdown 渲染工具，支持词性标注高亮。"
    )
    parser.add_argument(
        "file",
        help="path to the markdown file to render"
    )
    parser.add_argument(
        "--no-pos",
        action="store_true",
        help="disable pos tagging and use standard rendering"
    )
    
    args = parser.parse_args()
    render_markdown(args.file, enable_pos=not args.no_pos)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\noperation cancelled by user.")
        sys.exit(0)
