import argparse
import getpass
import sys
from typing import Optional
from rich.console import Console
from rich.table import Table

from super_md.api_client import APIClient
from super_md.utils import save_auth_token
from super_md.utils import get_auth_token
from super_md.utils import remove_config


BASE_URL = "http://localhost:8080"

console = Console()

def login_command(args):
    username = args.username or input("username: ")
    password = args.password or getpass.getpass("Password: ")
    
    client = APIClient()
    
    if client.login(username, password):
        if client.token:
            save_auth_token(client.token)
        console.print("[green]✓ Connection successful![/green]")
    else:
        console.print("[red]✗ Login failed[/red]")
        sys.exit(1)

def publish_command(args):
    client = APIClient()
    
    # Charger le token depuis la configuration
    token = get_auth_token()

    if token == None:
        console.print("[red]Your are not connected, please login to proceed this operation[/red]")
        return
    
    if token:
        client.token = token
        client.session.headers.update({
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        })
    
    if client.publish_document(args.file, args.folder):
        console.print("[green]✓ Publication complete[/green]")
    else:
        console.print("[red]✗ Publication failed[/red]")
        sys.exit(1)
def logout_command(args):

    remove_config()

    console.print("[yellow]Your account has been logged out[/yellow]")

def show_command(args):
    client = APIClient()
    token = get_auth_token()
    
    if token == None:
        console.print("[red]Your are not connected, please login to proceed this operation[/red]")
        return
    
    if token:
        client.token = token
        client.session.headers.update({
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        })
    
    documents = client.list_documents(args.folder)

    target_model = "space"

    if args.folder != None:
        target_model = "publication"
    
    if documents:
        
        listing = []
        if target_model == "space":
            listing = documents["space"]
            
            table = Table(title=f"Folders listing :", show_lines=True)
            table.add_column("Nom", style="white")
            table.add_column("Description", style="yellow")
            table.add_column("Goal", style="green")
            table.add_column("Link", style="white")
            
            for doc in listing:
                table.add_row(
                    doc.get('name', 'N/A'),
                    doc.get('description', 'N/A'),
                    doc.get('goal', 'N/A'),
                    BASE_URL+doc.get('link', 'N/A'),
                )
        
        if target_model == "publication":
            listing = documents["publication"][0]
            listing_space = documents["space"][0][0]
            
            listing_folders = documents["sub_space"][0]
            print(listing_folders)
            table = Table(title=f"Details Folder "+listing_space.get('name', 'N/A')+" :", show_lines=True)
            table.add_column("Name / Title", style="white")
            table.add_column("Folder", style="yellow")
            table.add_column("Link", style="white")

            for subs in listing_folders:
                table.add_row(
                    "[bold yellow]"+subs.get('name', 'N/A')+"[/bold yellow] (Folder)",
                    listing_space.get('name', 'N/A'),
                    "[bold green]"+BASE_URL+subs.get('link', 'N/A')+"[/bold green]",
                )
            
            for doc in listing:
                table.add_row(
                    doc.get('title', 'N/A'),
                    listing_space.get('name', 'N/A'),
                    BASE_URL+doc.get('link', 'N/A'),
                )
        
        console.print(table)
    else:
        console.print("[yellow]No publications found[/yellow]")

def main():
    #print("Super MD CLI")
    parser = argparse.ArgumentParser(
        description="CLI for interacting with the Super Markdown platform API"
    )
    subparsers = parser.add_subparsers(dest="command", help="Commands available")
    
    # Commande login
    login_parser = subparsers.add_parser("login", help="Authentication")
    login_parser.add_argument("-u", "--username", help="Username")
    login_parser.add_argument("-p", "--password", help="Password")
    login_parser.set_defaults(func=login_command)
    
    # Commande publish
    publish_parser = subparsers.add_parser("publish", help="Publish a Markdown document")
    publish_parser.add_argument("file", help="Path to the *.md / *.smd file to publish")
    publish_parser.add_argument("-f", "--folder", 
                               default="default",
                               help="Destination folder (default: default)")
    publish_parser.set_defaults(func=publish_command)
    
    # Commande show
    show_parser = subparsers.add_parser("show", help="List of publications")
    show_parser.add_argument("-f", "--folder",  help="Target folder name (optional)")
    show_parser.set_defaults(func=show_command)


    # Commande logout
    logout_parser = subparsers.add_parser("logout", help="Disconnect from your account locally")
    logout_parser.set_defaults(func=logout_command)
    
    # Parser les arguments
    args = parser.parse_args()
    
    if hasattr(args, 'func'):
        args.func(args)
    else:
        parser.print_help()

if __name__ == "__main__":
    main()