import argparse
import os
import json
from pathlib import Path
from eduslip.auth_controller import is_user_subscribed
from eduslip.slip_controller import get_slip

ALL_SUBJECTS = ["os", "java", "php", "dsa"]

def main():
    parser = argparse.ArgumentParser(description="Eduslip CLI")
    parser.add_argument("username", help="Your username")
    parser.add_argument("subject", help="Subject (os/java/php)")
    parser.add_argument("slip_number", type=int, help="Slip number")
    args = parser.parse_args()

    subject = args.subject.lower()

    if subject not in ALL_SUBJECTS:
        print(f'Invalid subject "{args.subject}". Available: {", ".join(ALL_SUBJECTS)}')
        return

    # subject ranges
    if subject == "os" and not (1 <= args.slip_number <= 25):
        print("Invalid slip number for OS. Valid range: 1–25")
        return
    if subject == "php" and not (1 <= args.slip_number <= 30):
        print("Invalid slip number for PHP. Valid range: 1–30")
        return
    if subject == "java" and not (1 <= args.slip_number <= 30):
        print("Invalid slip number for JAVA. Valid range: 1–30")
        return
    if subject == "dsa" and not (1 <= args.slip_number <= 25):
        print("Invalid slip number for DSA. Valid range: 1–25")
        return

    # Check subscription
    subscription = is_user_subscribed(args.username)
    if not subscription.get("success"):
        print(f"[ERROR] {subscription.get('message', 'Subscription check failed')}")
        return

    print(f'[INFO] User "{args.username}" subscription validated.')

    # Get slip
    slip = get_slip(subject, args.slip_number)
    if not slip:
        print("[ERROR] Slip not found.")
        return

    # Write files
    home_dir = Path.home()
    for question in slip["questions"]:
        for filename in question["filenames"]:
            code = slip["answers"].get(filename, "")
            file_path = home_dir / filename
            file_path.parent.mkdir(parents=True, exist_ok=True)
            if filename.endswith(".ipynb") and isinstance(code, dict):
                file_path.write_text(json.dumps(code, indent=2), encoding="utf-8")
            else:
                # For .py, .java, .c, .html, .txt, etc.
                file_path.write_text(code, encoding="utf-8")
            print(f"[SUCCESS] File created: {file_path}")
