"""
GetCanvas CLI.
"""

import argparse
import json
import os
import sys
from pathlib import Path
from typing import Optional

from .downloader import CanvasDownloader
from .converter import convert_all_pptx_in_folder
from .summarizer import process_pdfs_in_folder

DEFAULT_MODEL = "gemini-3-flash-preview"
CONFIG_FILE = Path.home() / ".getcanvas" / "config.json"


def load_config() -> dict:
    if not CONFIG_FILE.exists():
        return {}
    with open(CONFIG_FILE, "r") as f:
        return json.load(f)


def save_config(config: dict):
    CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
    with open(CONFIG_FILE, "w") as f:
        json.dump(config, f, indent=2)


def get_canvas_url() -> str:
    if os.getenv("CANVAS_URL"):
        return os.getenv("CANVAS_URL")
    
    config = load_config()
    if config.get("canvas_url"):
        return config["canvas_url"]
    
    print("=" * 50)
    print("Canvas URL not configured!")
    print("=" * 50)
    print("\nExamples:")
    print("  https://canvas.tue.nl")
    print("  https://canvas.stanford.edu")
    print("  https://canvas.instructure.com\n")
    
    url = input("Enter your Canvas URL: ").strip().rstrip("/")
    
    if not url:
        print("No URL provided. Exiting.")
        sys.exit(1)
    
    config["canvas_url"] = url
    save_config(config)
    print(f"URL saved to: {CONFIG_FILE}\n")
    
    return url


def get_canvas_token() -> str:
    if os.getenv("CANVAS_TOKEN"):
        return os.getenv("CANVAS_TOKEN")
    
    config = load_config()
    if config.get("canvas_token"):
        return config["canvas_token"]
    
    print("=" * 50)
    print("Canvas token not found!")
    print("=" * 50)
    print("\nTo get a token:")
    print("  1. Log into Canvas")
    print("  2. Go to Account > Settings")
    print("  3. Click '+ New Access Token'\n")
    
    token = input("Enter your Canvas token: ").strip()
    
    if not token:
        print("No token provided. Exiting.")
        sys.exit(1)
    
    config["canvas_token"] = token
    save_config(config)
    print(f"Token saved to: {CONFIG_FILE}\n")
    
    return token


def get_gemini_key() -> Optional[str]:
    if os.getenv("GEMINI_API_KEY"):
        return os.getenv("GEMINI_API_KEY")
    
    config = load_config()
    if config.get("gemini_key"):
        return config["gemini_key"]
    
    print("=" * 50)
    print("Gemini API key (optional)")
    print("=" * 50)
    print("\nFor AI summaries, get a key at: https://aistudio.google.com/")
    print("Press Enter to skip.\n")
    
    key = input("Enter your Gemini API key: ").strip()
    
    if not key:
        print("Skipping AI summaries.\n")
        return None
    
    config["gemini_key"] = key
    save_config(config)
    print(f"Key saved to: {CONFIG_FILE}\n")
    
    return key


def main():
    parser = argparse.ArgumentParser(
        prog="getcanvas",
        description="Download Canvas course, convert PPTX to PDF, generate AI summaries.",
    )

    parser.add_argument("course", help="Canvas course ID")
    parser.add_argument("-o", "--output", default="./canvas_content", help="Output folder")
    parser.add_argument("--reset", action="store_true", help="Reset all saved config")

    args = parser.parse_args()

    if args.reset:
        config = load_config()
        cleared = []
        for key in ["canvas_url", "canvas_token", "gemini_key"]:
            if key in config:
                del config[key]
                cleared.append(key)
        if cleared:
            save_config(config)
            print(f"Cleared: {', '.join(cleared)}")
        else:
            print("No saved config found.")
    
    canvas_url = get_canvas_url()
    canvas_token = get_canvas_token()
    gemini_key = get_gemini_key()
    
    output_dir = Path(args.output).resolve()
    base_url = f"{canvas_url}/api/v1"

    print(f"\n{'='*50}")
    print("GetCanvas")
    print(f"{'='*50}")
    print(f"Course: {args.course}")
    print(f"Output: {output_dir}")
    print(f"{'='*50}\n")

    print("[1/3] Downloading Canvas content...\n")
    downloader = CanvasDownloader(canvas_token, args.course, base_url)
    if not downloader.verify_token():
        print("\nToken may be expired. Run with --reset to reconfigure.")
        sys.exit(1)
    downloader.download_course(output_dir)

    print("\n[2/3] Converting PPTX to PDF...\n")
    if sys.platform == "win32":
        convert_all_pptx_in_folder(output_dir, delete_originals=True)
    else:
        print("Skipping: PPTX conversion requires Windows + PowerPoint.")

    if gemini_key:
        print(f"\n[3/3] Generating AI summaries ({DEFAULT_MODEL})...\n")
        process_pdfs_in_folder(output_dir, gemini_key, DEFAULT_MODEL)
    else:
        print("\n[3/3] Skipping AI summaries (no Gemini key).")

    print(f"\n{'='*50}")
    print(f"Done! Content saved to: {output_dir}")
    print(f"{'='*50}\n")


if __name__ == "__main__":
    main()



