From c3926641af546764bf847795b3d8d05d0f5a47e2 Mon Sep 17 00:00:00 2001
From: "Yandrik (aider)" <me@yandrik.dev>
Date: Thu, 20 Mar 2025 11:30:57 +0100
Subject: [PATCH] refactor: implement Rust-like error handling using Result
 types

---
 anki.py | 35 +++++++++++++++++++++++++++++------
 main.py | 14 ++++++++++++--
 2 files changed, 41 insertions(+), 8 deletions(-)

diff --git a/anki.py b/anki.py
index 15052e3..5d4f9a4 100644
--- a/anki.py
+++ b/anki.py
@@ -1,27 +1,46 @@
+from result import Result, Ok, Err
 import requests
 import logging
 from typing import List, Dict
 
 logger = logging.getLogger("flashcard-creator")
 
+class AnkiError(Exception):
+    """Base class for Anki-related errors"""
+    pass
+
+class ConnectionError(AnkiError):
+    """Error connecting to AnkiConnect"""
+    pass
+
+class DeckError(AnkiError):
+    """Error related to deck operations"""
+    pass
+
+class CardError(AnkiError):
+    """Error related to card operations"""
+    pass
 
 class AnkiConnect:
     def __init__(self, url="http://127.0.0.1:8765"):
         self.url = url
 
-    def get_decks(self) -> List[str]:
+    def get_decks(self) -> Result[List[str], AnkiError]:
         """Get the list of decks from Anki using AnkiConnect."""
         try:
             response = requests.post(
                 self.url, json={"action": "deckNames", "version": 6}
             )
             data = response.json()
-            return data.get("result", [])
+            return Ok(data.get("result", []))
+        except requests.exceptions.RequestException as e:
+            logger.error(f"Connection error getting Anki decks: {e}")
+            return Err(ConnectionError(f"Failed to connect to Anki: {e}"))
         except Exception as e:
             logger.error(f"Error getting Anki decks: {e}")
-            return []
+            return Err(DeckError(f"Failed to get decks: {e}"))
 
-    def create_cards(self, deck: str, cards: List[Dict[str, str]]) -> bool:
+    def create_cards(self, deck: str, cards: List[Dict[str, str]]) -> Result[bool, AnkiError]:
         """Create flashcards in Anki using AnkiConnect."""
         try:
             # Prepare notes for addition
@@ -48,9 +67,13 @@ class AnkiConnect:
             success = all(id is not None for id in data.get("result", []))
             if success:
                 logger.info("Successfully added all cards to Anki")
+                return Ok(True)
             else:
                 logger.warning("Some cards failed to be added to Anki")
-            return success
+                return Err(CardError("Some cards failed to be added"))
+        except requests.exceptions.RequestException as e:
+            logger.error(f"Connection error creating Anki cards: {e}")
+            return Err(ConnectionError(f"Failed to connect to Anki: {e}"))
         except Exception as e:
             logger.error(f"Error creating Anki cards: {e}")
-            return False
+            return Err(CardError(f"Failed to create cards: {e}"))
diff --git a/main.py b/main.py
index 84dcec2..ffe7353 100644
--- a/main.py
+++ b/main.py
@@ -641,11 +641,21 @@ class FlashcardCreator:
 
     def get_anki_decks(self) -> List[str]:
         """Get the list of decks from Anki using AnkiConnect."""
-        return self.anki.get_decks()
+        result = self.anki.get_decks()
+        if isinstance(result, Ok):
+            return result.value
+        else:
+            logger.error(f"Error getting Anki decks: {result.value}")
+            return []
 
     def create_anki_cards(self, deck: str, cards: List[Dict[str, str]]) -> bool:
         """Create flashcards in Anki using Anki-connect."""
-        return self.anki.create_cards(deck, cards)
+        result = self.anki.create_cards(deck, cards)
+        if isinstance(result, Ok):
+            return result.value
+        else:
+            logger.error(f"Error creating Anki cards: {result.value}")
+            return False
 
     def export_as_yaml(self, e):
         """Export the flashcards as a YAML file."""