# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.

# %% auto 0
__all__ = ['MarkdownHandler']

# %% ../nbs/00_core.ipynb 2
from fastcore.basics import *
from fastcore.foundation import *
from fastcore.test import *
from fastcore.script import call_parse, Param

from pathlib import Path
import re, time
import threading

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class MarkdownHandler(FileSystemEventHandler):
    """Handles markdown file events and extracts code blocks"""
    def __init__(self, output_dir='py'):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)
    
    def should_process(self, path):
        "Check if the markdown file should be processed"
        return path.suffix == '.md' and path.name.lower() != 'readme.md'
    
    def on_modified(self, event):
        path = Path(event.src_path)
        if not self.should_process(path): return
        self.process_markdown(path)
        
    def on_created(self, event):
        path = Path(event.src_path)
        if not self.should_process(path): return
        self.process_markdown(path)
        
    def process_markdown(self, md_path):
        "Process a markdown file and save extracted code"
        content = md_path.read_text()
        code = self.extract_code(content)
        if code:
            py_path = self.output_dir/f"{md_path.stem}.py"
            py_path.write_text(code)

    def extract_code(self, md_content):
        "Extract code blocks from markdown content"
        # Match both single and triple backtick code blocks
        pattern = r'`{3}[\w\s]*\n(.*?)`{3}|`([^`]+)`'
        code_blocks = []
        for match in re.finditer(pattern, md_content, re.DOTALL):
            # Get whichever group matched (triple or single backticks)
            code = match.group(1) or match.group(2)
            if code: code_blocks.append(code)
        return '\n'.join(code_blocks)
