"""
CLI commands — only two: notes and update.
"""

import click

from ktunotes import __version__
from ktunotes.ui import print_banner, show_success, show_error, show_info
from ktunotes.cache import get_subject, update_cache, load_cache
from ktunotes.downloader import download_folder
from ktunotes.utils import open_in_browser


@click.group(invoke_without_command=True)
@click.version_option(version=__version__, prog_name="ktunotes")
@click.pass_context
def cli(ctx):
    """KTU Notes CLI — Fast notes downloader for ktunotes.live."""
    if ctx.invoked_subcommand is None:
        print_banner()
        click.echo("  Usage:")
        click.echo("    ktunotes notes <subject-code>   Download notes for a subject")
        click.echo("    ktunotes update                 Update the subject cache")
        click.echo()


@cli.command()
@click.argument("subject_code")
def notes(subject_code):
    """Download notes for a subject by its code."""
    code = subject_code.lower()

    # Look up subject
    subject = get_subject(code)

    if not subject:
        show_error(f"Subject '{code}' not found in cache.")
        show_info("Run 'ktunotes update' to refresh the cache.")
        return

    name = subject.get("name", code)
    gdrive = subject.get("gdrive", "")

    print()
    show_info(f"Subject: {code.upper()} — {name}")

    if not gdrive:
        show_error("No Google Drive link found for this subject.")
        return

    # Download the folder
    print()
    download_folder(gdrive, code)

    # Open in browser
    print()
    show_info("Opening Google Drive folder...")
    open_in_browser(gdrive)


@cli.command()
def update():
    """Update the local subject cache by scraping ktunotes.live."""
    print()
    show_info("Updating subject cache...")

    data = update_cache()
    count = len(data)

    if count > 0:
        show_success(f"Cache updated. {count} subjects found.")
    else:
        show_error("Scraping returned no subjects. Check your connection.")
    print()
