import os
import sys
import shutil

from text_extractor.extractor import (
    TextExtractor,
    download_drive_folder_any
)


def main():
    print("=== File Text Extractor ===")

    if len(sys.argv) < 2:
        print("Usage:")
        print("  python -m text_extractor.cli <folder_path | google_drive_link>")
        sys.exit(1)

    user_input = sys.argv[1].strip().strip('"')
    TEMP_FOLDER = "temp_drive_download"

    # ---------------- Google Drive ----------------
    if "drive.google.com" in user_input:
        print("🔐 Google login will open in browser (first time only)...")

        try:
            download_drive_folder_any(user_input, TEMP_FOLDER)
        except Exception as e:
            print("❌ Failed to download Google Drive folder")
            print(e)
            sys.exit(1)

        folder_path = TEMP_FOLDER

    # ---------------- Local Folder ----------------
    else:
        folder_path = user_input

    # ---------------- Validation ----------------
    if not os.path.exists(folder_path):
        print("❌ Folder does not exist:", folder_path)
        sys.exit(1)

    if not os.path.isdir(folder_path):
        print("❌ Provided path is not a folder:", folder_path)
        sys.exit(1)

    # ---------------- Extraction ----------------
    extractor = TextExtractor()
    results = extractor.extract_from_folder(folder_path)

    if not results:
        print("⚠️ No supported files found.")
        return

    for file_path, text in results.items():
        print("\n" + "=" * 80)
        print(f"FILE: {file_path}")
        print("-" * 80)
        if text.strip():
            print(text[:3000])
        else:
            print("[No text extracted]")

    # ---------------- Cleanup ----------------
    if folder_path == TEMP_FOLDER:
        shutil.rmtree(TEMP_FOLDER, ignore_errors=True)


if __name__ == "__main__":
    main()
