#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 28 12:40:08 2025

@author: samd
"""
import bilbystats as bs
import os
import re

def gen_code(prompt, example_usage, savename, savedir, model = 'anthropic/claude-sonnet-4.5', max_tokens = 10000):
    addon = '\nProvide only the Python code without explanations.'
    
    code = bs.llm_api(prompt + addon, '', model, max_tokens = max_tokens)
    code = bs.process_python_string(code)
    
    with open(savedir + savename + '.py', "w") as file:
        file.write(code)
        
    return code

def locate_str(string, dir, ending = '.py'):
    results = []
    
    for root, dirs, files in os.walk(dir):
        for file in files:
            if file.endswith(ending):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                        if string in content:
                            results.append(file_path)
                except Exception as e:
                    pass
    
    return results

def locate_fun(fun_name, dir = '/Users/samd/Documents/Packages/bilbystats/bilbystats/'):
    results = locate_str('def ' + fun_name + '(', dir)
    results += locate_str('async def ' + fun_name + '(', dir)
    
    if len(results) > 0:
        results = results[0]
    else:
        results = locate_fun2(fun_name, dir)
    
    return results

def locate_fun2(fun_name, dir = '/Users/samd/Documents/Packages/bilbystats/bilbystats/'):
    results = locate_str('def ' + fun_name, dir)
    results += locate_str('async def ' + fun_name, dir)
    
    return results

def extract_fun(fun_name, dir = '/Users/samd/Documents/Packages/bilbystats/bilbystats/'):
    function_file = bs.locate_fun(fun_name, dir)
    fns_in_file = bs.split2functions(function_file)

    results = bs.prefix_strings(fns_in_file, 'def ' + fun_name + '(')
    results += bs.prefix_strings(fns_in_file, 'async def ' + fun_name + '(')
    results = results[0]
    
    return results

def fun_edit(fun_name, directory = '/Users/samd/Documents/Packages/bilbystats/bilbystats/'):
    filename = locate_fun(fun_name, directory)
    #line = bs.string_line(filename, "def ' + fun_name + '('")
    #if len(line) == 0:
    #    line = bs.string_line(filename, "'async def ' + fun_name + '('")

    bs.edit(filename)

def gen_examples(function_name, n_examples = 3):
    prompt = 'Create ' + str(n_examples) + ' python code examples of using this function: '
    prompt += ' Separate each example with a line: #%%'
    addon = '\nProvide only the Python code without explanations.'
    prompt = prompt + addon
    
    return 

#def test_code(savename, savedir):
    