#!/usr/bin/env python3
"""
OpenDraft CLI - AI-Powered Research Paper Generator

A simple, interactive command-line tool for generating academic papers.
"""

import sys

# Check Python version early
if sys.version_info < (3, 9):
    print("\n  OpenDraft requires Python 3.9 or higher.")
    print(f"  You have Python {sys.version_info.major}.{sys.version_info.minor}")
    print("\n  Fix:")
    print("    conda create -n opendraft python=3.11 -y")
    print("    conda activate opendraft")
    print("    pip install opendraft")
    print()
    sys.exit(1)

import os
import json
from pathlib import Path

from opendraft.version import __version__

# Config directory for storing API keys
CONFIG_DIR = Path.home() / '.opendraft'
CONFIG_FILE = CONFIG_DIR / 'config.json'

# ANSI color codes
class Colors:
    PURPLE = '\033[95m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    WHITE = '\033[97m'
    GRAY = '\033[90m'
    BOLD = '\033[1m'
    DIM = '\033[2m'
    RESET = '\033[0m'
    UNDERLINE = '\033[4m'


def get_saved_config():
    """Load saved configuration."""
    if CONFIG_FILE.exists():
        try:
            return json.loads(CONFIG_FILE.read_text())
        except:
            return {}
    return {}


def save_config(config):
    """Save configuration to disk."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(json.dumps(config, indent=2))


def has_api_key():
    """Check if API key is configured."""
    if os.getenv('GOOGLE_API_KEY'):
        return True
    config = get_saved_config()
    return bool(config.get('google_api_key'))


def get_api_key():
    """Get API key from environment or config."""
    key = os.getenv('GOOGLE_API_KEY')
    if key:
        return key
    config = get_saved_config()
    return config.get('google_api_key', '')


def clear_screen():
    """Clear terminal screen."""
    os.system('cls' if os.name == 'nt' else 'clear')


def print_header():
    """Print clean header."""
    c = Colors
    print()
    print(f"  {c.PURPLE}{c.BOLD}OpenDraft{c.RESET} {c.GRAY}v{__version__}{c.RESET}")
    print(f"  {c.GRAY}AI Research Paper Generator{c.RESET}")
    print()


def print_divider():
    """Print a subtle divider."""
    print(f"  {Colors.GRAY}{'─' * 50}{Colors.RESET}")


def run_setup():
    """Interactive setup wizard."""
    c = Colors
    clear_screen()
    print_header()

    print(f"  {c.BOLD}Setup{c.RESET}")
    print_divider()
    print()
    print(f"  You need a {c.BOLD}Google AI API key{c.RESET} (free).")
    print()
    print(f"  {c.CYAN}1.{c.RESET} Open {c.UNDERLINE}https://aistudio.google.com/apikey{c.RESET}")
    print(f"  {c.CYAN}2.{c.RESET} Click {c.BOLD}Create API Key{c.RESET}")
    print(f"  {c.CYAN}3.{c.RESET} Copy and paste below")
    print()

    try:
        api_key = input(f"  {c.PURPLE}›{c.RESET} API Key: ").strip()
    except (KeyboardInterrupt, EOFError):
        print(f"\n\n  {c.GRAY}Cancelled.{c.RESET}\n")
        return False

    if not api_key:
        print(f"\n  {c.RED}✗{c.RESET} No key provided.\n")
        return False

    if len(api_key) < 20:
        print(f"\n  {c.RED}✗{c.RESET} Invalid key format.\n")
        return False

    config = get_saved_config()
    config['google_api_key'] = api_key
    save_config(config)
    os.environ['GOOGLE_API_KEY'] = api_key

    print()
    print(f"  {c.GREEN}✓{c.RESET} API key saved to {c.GRAY}~/.opendraft/config.json{c.RESET}")
    print()
    return True


def select_option(prompt, options, default=0):
    """Clean option selector with visible numbers."""
    c = Colors
    print(f"  {c.PURPLE}›{c.RESET} {prompt}")
    print()

    for i, (label, value) in enumerate(options):
        num = i + 1
        if i == default:
            print(f"    {c.PURPLE}{num}.{c.RESET} {c.BOLD}{label}{c.RESET} {c.GRAY}← default{c.RESET}")
        else:
            print(f"    {c.GRAY}{num}. {label}{c.RESET}")
    print()

    try:
        choice = input(f"  {c.GRAY}Enter 1-{len(options)} or press Enter:{c.RESET} ").strip()
    except (KeyboardInterrupt, EOFError):
        return None

    selected_idx = default
    if choice:
        try:
            idx = int(choice) - 1
            if 0 <= idx < len(options):
                selected_idx = idx
        except ValueError:
            pass

    # Show what was selected
    selected_label = options[selected_idx][0]
    print(f"  {c.GREEN}✓{c.RESET} {selected_label}")
    print()

    return options[selected_idx][1]


def run_interactive():
    """Run interactive paper generation."""
    c = Colors
    clear_screen()
    print_header()

    # Check for API key
    if not has_api_key():
        print(f"  {c.YELLOW}!{c.RESET} No API key configured.")
        print()
        if not run_setup():
            return 1
        clear_screen()
        print_header()
    else:
        if not os.getenv('GOOGLE_API_KEY'):
            os.environ['GOOGLE_API_KEY'] = get_api_key()

    print(f"  {c.BOLD}New Paper{c.RESET}")
    print_divider()
    print()

    # Get topic
    try:
        print(f"  {c.PURPLE}›{c.RESET} What's your research topic?")
        print()
        topic = input(f"    ").strip()
    except (KeyboardInterrupt, EOFError):
        print(f"\n\n  {c.GRAY}Cancelled.{c.RESET}\n")
        return 0

    if not topic:
        print(f"\n  {c.RED}✗{c.RESET} No topic provided.\n")
        return 1

    print()

    # Select level
    level = select_option(
        "Academic level",
        [
            ("Research paper", "research_paper"),
            ("Bachelor's thesis", "bachelor"),
            ("Master's thesis", "master"),
            ("PhD dissertation", "phd"),
        ],
        default=0
    )
    if level is None:
        return 0

    # Select citation style
    style = select_option(
        "Citation style",
        [
            ("APA 7th Edition", "apa"),
            ("MLA 9th Edition", "mla"),
            ("Chicago", "chicago"),
            ("IEEE", "ieee"),
        ],
        default=0
    )
    if style is None:
        return 0

    # Select language
    language = select_option(
        "Language",
        [
            ("English", "en"),
            ("German (Deutsch)", "de"),
        ],
        default=0
    )
    if language is None:
        return 0

    # Confirm
    print_divider()
    print()
    level_display = level.replace("_", " ").title()
    lang_display = "English" if language == "en" else "German"
    print(f"  {c.GRAY}Topic{c.RESET}     {topic}")
    print(f"  {c.GRAY}Level{c.RESET}     {level_display}")
    print(f"  {c.GRAY}Style{c.RESET}     {style.upper()}")
    print(f"  {c.GRAY}Language{c.RESET}  {lang_display}")
    print()
    print_divider()
    print()

    try:
        confirm = input(f"  {c.PURPLE}›{c.RESET} Generate paper? {c.GRAY}[Y/n]{c.RESET} ").strip().lower()
    except (KeyboardInterrupt, EOFError):
        print(f"\n\n  {c.GRAY}Cancelled.{c.RESET}\n")
        return 0

    if confirm and confirm not in ['y', 'yes', '']:
        print(f"\n  {c.GRAY}Cancelled.{c.RESET}\n")
        return 0

    # Start generation
    print()
    print(f"  {c.PURPLE}⣾{c.RESET} Generating paper...")
    print(f"  {c.GRAY}  This takes about 10-15 minutes.{c.RESET}")
    print()

    try:
        from draft_generator import generate_draft

        output_dir = Path.cwd() / 'opendraft_output'

        pdf_path, docx_path = generate_draft(
            topic=topic,
            language=language,
            academic_level=level,
            output_dir=output_dir,
            skip_validation=True,
            verbose=True
        )

        print()
        print_divider()
        print()
        print(f"  {c.GREEN}✓{c.RESET} {c.BOLD}Paper ready{c.RESET}")
        print()
        print(f"  {c.GRAY}PDF{c.RESET}   {pdf_path}")
        print(f"  {c.GRAY}Word{c.RESET}  {docx_path}")
        print()

        # Open output folder
        try:
            import subprocess
            exports_dir = output_dir / 'exports'
            if sys.platform == 'darwin':
                subprocess.run(['open', str(exports_dir)], check=False)
            elif sys.platform == 'win32':
                subprocess.run(['explorer', str(exports_dir)], check=False)
            elif sys.platform.startswith('linux'):
                subprocess.run(['xdg-open', str(exports_dir)], check=False)
        except:
            pass

        return 0

    except KeyboardInterrupt:
        print(f"\n\n  {c.YELLOW}!{c.RESET} Generation interrupted.\n")
        return 1
    except Exception as e:
        print()
        print(f"  {c.RED}✗{c.RESET} {e}")
        print()
        return 1


def main():
    """Main CLI entry point."""
    import argparse

    parser = argparse.ArgumentParser(
        prog="opendraft",
        description="AI-Powered Research Paper Generator",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=f"""
{Colors.BOLD}Usage:{Colors.RESET}
  opendraft                    Interactive mode
  opendraft setup              Configure API key
  opendraft "Your Topic"       Quick generate

{Colors.BOLD}Examples:{Colors.RESET}
  opendraft "Impact of AI on Education"
  opendraft "Climate Change Mitigation" --level phd

{Colors.GRAY}https://opendraft.ai{Colors.RESET}
        """
    )

    parser.add_argument(
        "--version", "-v",
        action="version",
        version=f"opendraft {__version__}"
    )

    parser.add_argument(
        "topic",
        nargs="?",
        help="Research topic (or 'setup')"
    )

    parser.add_argument(
        "--level", "-l",
        choices=["research_paper", "bachelor", "master", "phd"],
        default="research_paper",
        help="Academic level"
    )

    parser.add_argument(
        "--style", "-s",
        choices=["apa", "mla", "chicago", "ieee"],
        default="apa",
        help="Citation style"
    )

    parser.add_argument(
        "--output", "-o",
        type=Path,
        help="Output directory"
    )

    args = parser.parse_args()
    c = Colors

    # Handle 'setup' command
    if args.topic and args.topic.lower() == 'setup':
        return 0 if run_setup() else 1

    # Interactive mode
    if not args.topic:
        return run_interactive()

    # Quick mode
    clear_screen()
    print_header()

    if not has_api_key():
        print(f"  {c.YELLOW}!{c.RESET} Run {c.BOLD}opendraft setup{c.RESET} first.\n")
        return 1

    if not os.getenv('GOOGLE_API_KEY'):
        os.environ['GOOGLE_API_KEY'] = get_api_key()

    print(f"  {c.GRAY}Topic{c.RESET}  {args.topic}")
    print(f"  {c.GRAY}Level{c.RESET}  {args.level}")
    print(f"  {c.GRAY}Style{c.RESET}  {args.style.upper()}")
    print()
    print(f"  {c.PURPLE}⣾{c.RESET} Generating...")
    print()

    try:
        from draft_generator import generate_draft

        output_dir = args.output or Path.cwd() / 'opendraft_output'

        pdf_path, docx_path = generate_draft(
            topic=args.topic,
            language="en",
            academic_level=args.level,
            output_dir=output_dir,
            skip_validation=True,
            verbose=True
        )

        print()
        print(f"  {c.GREEN}✓{c.RESET} {c.BOLD}Done{c.RESET}")
        print(f"  {c.GRAY}PDF{c.RESET}   {pdf_path}")
        print(f"  {c.GRAY}Word{c.RESET}  {docx_path}")
        print()
        return 0

    except KeyboardInterrupt:
        print(f"\n\n  {c.YELLOW}!{c.RESET} Interrupted.\n")
        return 1
    except Exception as e:
        print(f"  {c.RED}✗{c.RESET} {e}")
        return 1


if __name__ == "__main__":
    sys.exit(main())
