"""Language Reference Handbook service for built-in functions, methods, primitive types, and topics."""
import httpx
from typing import Dict, List, Any
from src.core.config import config
from src.core.mentor import get_chat_completions_url
from src.core.registry import registry

HANDBOOK_CATALOG: Dict[str, Dict[str, List[Dict[str, str]]]] = {
    "python": {
        "functions": [
            {"id": "type_int", "title": "int", "desc": "Integer numerical data type (e.g. 42, -7)."},
            {"id": "type_float", "title": "float", "desc": "Floating-point real numerical data type (e.g. 3.14159)."},
            {"id": "type_bool", "title": "bool", "desc": "Boolean truth value type (True or False)."},
            {"id": "type_str", "title": "str", "desc": "Immutable text string data type."},
            {"id": "type_list", "title": "list", "desc": "Mutable ordered sequence collection type."},
            {"id": "type_dict", "title": "dict", "desc": "Key-value dictionary mapping collection type."},
            {"id": "type_set", "title": "set", "desc": "Unordered collection of unique items."},
            {"id": "type_tuple", "title": "tuple", "desc": "Immutable ordered sequence collection."},
            {"id": "print", "title": "print()", "desc": "Prints specified objects to standard output."},
            {"id": "input", "title": "input()", "desc": "Reads line from standard input as string."},
            {"id": "len", "title": "len()", "desc": "Returns the number of items in a container."},
            {"id": "range", "title": "range()", "desc": "Generates a sequence of numbers from start to stop."},
            {"id": "enumerate", "title": "enumerate()", "desc": "Yields index and value tuples from an iterable."},
            {"id": "zip", "title": "zip()", "desc": "Iterates over multiple iterables in parallel."},
            {"id": "map", "title": "map()", "desc": "Applies function to all items in an iterable."},
            {"id": "filter", "title": "filter()", "desc": "Filters elements of iterable where predicate is True."},
            {"id": "sorted", "title": "sorted()", "desc": "Returns new sorted list from items in iterable."},
            {"id": "isinstance", "title": "isinstance()", "desc": "Checks if object is an instance of a class."},
            {"id": "type_func", "title": "type()", "desc": "Returns the type of an object."},
            {"id": "open", "title": "open()", "desc": "Opens a file and returns file object."},
            {"id": "str_split", "title": "str.split()", "desc": "Splits string into list using delimiter."},
            {"id": "str_join", "title": "str.join()", "desc": "Concatenates string elements with separator."},
            {"id": "str_replace", "title": "str.replace()", "desc": "Replaces occurrences of substring."},
            {"id": "dict_get", "title": "dict.get()", "desc": "Returns value for key or default if missing."},
            {"id": "list_append", "title": "list.append()", "desc": "Appends item to end of list."},
            {"id": "sum", "title": "sum()", "desc": "Sums items of an iterable."},
            {"id": "min_max", "title": "min() / max()", "desc": "Returns smallest or largest item."},
            {"id": "abs", "title": "abs()", "desc": "Returns absolute value of number."},
            {"id": "round", "title": "round()", "desc": "Rounds float to given precision."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitive Types", "desc": "int, float, bool, str, dynamic typing, mutability."},
            {"id": "control", "title": "Control Flow & Loops", "desc": "if, elif, else, for, while, break, continue, pass."},
            {"id": "funcs", "title": "Functions & Type Hints", "desc": "def, return, lambda, *args, **kwargs, docstrings."},
            {"id": "collections", "title": "Lists, Dicts, Sets & Tuples", "desc": "Comprehensions, operations, set math, tuple unpacking."},
            {"id": "errors", "title": "Exception Handling", "desc": "try, except, else, finally, raise, custom exceptions."},
            {"id": "oop", "title": "Classes & OOP Concepts", "desc": "class, __init__, self, inheritance, super(), dunder methods."},
            {"id": "modules", "title": "Modules & Standard Library", "desc": "import, math, sys, os, json, random, datetime."},
            {"id": "decorators", "title": "Decorators & Generators", "desc": "@decorator syntax, yield, generator expressions."},
        ],
    },
    "java": {
        "functions": [
            {"id": "type_int", "title": "int / long", "desc": "32-bit and 64-bit primitive signed integer data types."},
            {"id": "type_boolean", "title": "boolean", "desc": "Primitive boolean data type (true or false)."},
            {"id": "type_double", "title": "float / double", "desc": "Single and double precision floating point types."},
            {"id": "type_char", "title": "char", "desc": "Single 16-bit Unicode character primitive."},
            {"id": "type_string", "title": "String", "desc": "Immutable sequence of characters in Java."},
            {"id": "sys_out", "title": "System.out.println()", "desc": "Prints text to standard output with newline."},
            {"id": "sys_print", "title": "System.out.print()", "desc": "Prints text to standard output without newline."},
            {"id": "scanner_next", "title": "Scanner.nextLine()", "desc": "Reads line of user input from System.in."},
            {"id": "str_length", "title": "String.length()", "desc": "Returns total character count of string."},
            {"id": "str_char_at", "title": "String.charAt()", "desc": "Returns character at specified 0-based index."},
            {"id": "str_substring", "title": "String.substring()", "desc": "Extracts substring between start and end index."},
            {"id": "str_equals", "title": "String.equals()", "desc": "Compares two strings for content equality."},
            {"id": "str_split", "title": "String.split()", "desc": "Splits string into array using regex delimiter."},
            {"id": "str_replace", "title": "String.replace()", "desc": "Replaces all target character sequences."},
            {"id": "math_abs", "title": "Math.abs()", "desc": "Returns absolute positive value of number."},
            {"id": "math_max", "title": "Math.max() / Math.min()", "desc": "Returns greater or lesser of two numerical values."},
            {"id": "math_pow", "title": "Math.pow()", "desc": "Raises base to exponent power (e.g. Math.pow(2, 3) = 8)."},
            {"id": "math_sqrt", "title": "Math.sqrt()", "desc": "Returns square root of a double value."},
            {"id": "math_random", "title": "Math.random()", "desc": "Returns pseudo-random double between 0.0 and 1.0."},
            {"id": "arrays_sort", "title": "Arrays.sort()", "desc": "Sorts primitive or object array in ascending order."},
            {"id": "list_add", "title": "List.add()", "desc": "Appends element to Java List collection."},
            {"id": "list_get", "title": "List.get()", "desc": "Returns element at specified index in List."},
            {"id": "list_size", "title": "List.size()", "desc": "Returns number of elements in collection."},
            {"id": "map_put", "title": "Map.put() / Map.get()", "desc": "Stores key-value pair or retrieves value by key in HashMap."},
            {"id": "set_add", "title": "Set.add()", "desc": "Adds element to HashSet if not already present."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitive Types", "desc": "int, double, boolean, String, char, float, final, scope."},
            {"id": "control", "title": "Control Flow & Loops", "desc": "if, else if, else, switch, for, for-each, while, do-while."},
            {"id": "arrays", "title": "Arrays & Collections", "desc": "1D/2D arrays, ArrayList, HashMap, HashSet, Iterators."},
            {"id": "methods", "title": "Methods & Overloading", "desc": "Signatures, return values, parameters, method overloading, static."},
            {"id": "classes", "title": "Classes & OOP Concepts", "desc": "Classes, objects, constructors, encapsulation, getters/setters."},
            {"id": "inheritance", "title": "Inheritance & Polymorphism", "desc": "extends, super, method overriding, @Override, dynamic dispatch."},
            {"id": "interfaces", "title": "Interfaces & Abstraction", "desc": "abstract class, abstract methods, interface, implements, default methods."},
            {"id": "exceptions", "title": "Exception Handling", "desc": "try, catch, finally, throw, throws, custom Exception classes."},
            {"id": "generics", "title": "Generics & Type Safety", "desc": "Generic classes, <T>, List<T>, bounded wildcards (? extends T)."},
            {"id": "packages", "title": "Packages & Access Modifiers", "desc": "package, import, public, private, protected, package-private."},
        ],
    },
    "csharp": {
        "functions": [
            {"id": "type_int", "title": "int / long", "desc": "Signed 32-bit and 64-bit integer primitive types."},
            {"id": "type_bool", "title": "bool", "desc": "Boolean primitive type (true or false)."},
            {"id": "type_float", "title": "float / double / decimal", "desc": "Single, double, and high-precision financial decimal types."},
            {"id": "type_string", "title": "string", "desc": "UTF-16 text string type in C#."},
            {"id": "console_write", "title": "Console.WriteLine()", "desc": "Writes line terminator to standard output."},
            {"id": "console_read", "title": "Console.ReadLine()", "desc": "Reads next line of characters from stdin."},
            {"id": "str_length", "title": "string.Length", "desc": "Gets number of characters in string."},
            {"id": "str_substr", "title": "string.Substring()", "desc": "Retrieves substring starting at index."},
            {"id": "str_split", "title": "string.Split()", "desc": "Splits string into array based on separator."},
            {"id": "str_replace", "title": "string.Replace()", "desc": "Replaces all occurrences of string/char."},
            {"id": "str_contains", "title": "string.Contains()", "desc": "Checks if string contains specified substring."},
            {"id": "math_abs", "title": "Math.Abs()", "desc": "Returns absolute value of number."},
            {"id": "math_max", "title": "Math.Max() / Math.Min()", "desc": "Returns larger or smaller of two values."},
            {"id": "math_pow", "title": "Math.Pow()", "desc": "Raises number to specified power."},
            {"id": "math_sqrt", "title": "Math.Sqrt()", "desc": "Returns square root of a number."},
            {"id": "rand_next", "title": "Random.Next()", "desc": "Generates random non-negative integer."},
            {"id": "list_add", "title": "List<T>.Add()", "desc": "Adds object to end of List<T>."},
            {"id": "list_remove", "title": "List<T>.Remove()", "desc": "Removes first occurrence of specific object."},
            {"id": "dict_add", "title": "Dictionary<K,V>[key]", "desc": "Key-value pair map accessor in C#."},
            {"id": "linq_where", "title": "LINQ (.Where(), .Select())", "desc": "Language Integrated Query operations on collections."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitive Types", "desc": "var, int, bool, string, double, decimal, const, readonly."},
            {"id": "control", "title": "Control Flow & Switches", "desc": "if, else, switch expressions, for, foreach, while, do while."},
            {"id": "methods", "title": "Methods & Parameters", "desc": "Methods, ref, out, in, optional parameters, extension methods."},
            {"id": "classes", "title": "Classes, Structs & Records", "desc": "class, struct, record, properties (get; set;), constructors."},
            {"id": "inheritance", "title": "Inheritance & Polymorphism", "desc": "virtual, override, sealed, base, abstract classes."},
            {"id": "interfaces", "title": "Interfaces & Abstraction", "desc": "interface, explicit implementation, default interface methods."},
            {"id": "generics", "title": "Generics & Collections", "desc": "List<T>, Dictionary<K,V>, HashSet<T>, generic constraints."},
            {"id": "linq", "title": "LINQ & Lambda Expressions", "desc": "Query syntax, method syntax, delegates, Func<T>, Action<T>."},
            {"id": "exceptions", "title": "Exception Handling", "desc": "try, catch, finally, throw, exception filters (when)."},
        ],
    },
    "cpp": {
        "functions": [
            {"id": "type_int", "title": "int / long long", "desc": "Signed 32-bit and 64-bit integer primitive types."},
            {"id": "type_bool", "title": "bool", "desc": "Boolean primitive type (true or false)."},
            {"id": "type_double", "title": "float / double", "desc": "Single or double precision floating point."},
            {"id": "type_string", "title": "std::string", "desc": "Standard library C++ string class."},
            {"id": "type_vector", "title": "std::vector<T>", "desc": "Dynamic array sequence container."},
            {"id": "std_cout", "title": "std::cout / std::cin", "desc": "Standard stream output and input operations."},
            {"id": "std_getline", "title": "std::getline()", "desc": "Reads line from input stream into string."},
            {"id": "vec_push_back", "title": "std::vector::push_back()", "desc": "Adds element to end of vector."},
            {"id": "std_sort", "title": "std::sort()", "desc": "Sorts range [first, last) in ascending order."},
            {"id": "make_unique", "title": "std::make_unique()", "desc": "Constructs std::unique_ptr object."},
            {"id": "make_shared", "title": "std::make_shared()", "desc": "Constructs std::shared_ptr object."},
            {"id": "math_abs", "title": "std::abs()", "desc": "Returns absolute value of number."},
            {"id": "math_max", "title": "std::max() / std::min()", "desc": "Returns maximum or minimum of two values."},
            {"id": "math_pow", "title": "std::pow() / std::sqrt()", "desc": "Calculates power or square root of double."},
        ],
        "subjects": [
            {"id": "vars", "title": "Primitive Data Types", "desc": "int, float, double, bool, char, void, const, constexpr, auto."},
            {"id": "control", "title": "Control Flow & Loops", "desc": "if, else, for, range-based for (auto& x : vec), while, switch."},
            {"id": "pointers", "title": "Pointers & References", "desc": "Raw pointers (*), references (&), nullptr, address-of (&)."},
            {"id": "memory", "title": "Smart Pointers & Memory", "desc": "unique_ptr, shared_ptr, weak_ptr, RAII pattern."},
            {"id": "classes", "title": "Classes & OOP", "desc": "class, struct, public, private, protected, constructors, destructors."},
            {"id": "inheritance", "title": "Inheritance & Virtual Functions", "desc": "Inheritance, virtual, override, pure virtual (= 0), abstract classes."},
            {"id": "templates", "title": "Templates & Generics", "desc": "Function templates, class templates, generic programming."},
            {"id": "stl", "title": "STL Containers & Iterators", "desc": "vector, map, set, unordered_map, pair, iterators (begin, end)."},
            {"id": "exceptions", "title": "Exception Handling", "desc": "try, catch, throw, std::exception, noexcept."},
        ],
    },
    "javascript": {
        "functions": [
            {"id": "type_boolean", "title": "boolean", "desc": "Boolean primitive type (true or false)."},
            {"id": "type_number", "title": "number", "desc": "IEEE 754 floating-point numerical type."},
            {"id": "type_string", "title": "string", "desc": "Textual string primitive data type."},
            {"id": "console_log", "title": "console.log()", "desc": "Outputs message to debugging console."},
            {"id": "fetch", "title": "fetch()", "desc": "Asynchronously fetches network resource via HTTP."},
            {"id": "arr_map", "title": "Array.prototype.map()", "desc": "Creates new array with mapped elements."},
            {"id": "arr_filter", "title": "Array.prototype.filter()", "desc": "Filters elements satisfying predicate function."},
            {"id": "arr_reduce", "title": "Array.prototype.reduce()", "desc": "Executes reducer function across elements."},
            {"id": "arr_includes", "title": "Array.prototype.includes()", "desc": "Determines whether array contains value."},
            {"id": "arr_push", "title": "Array.prototype.push() / pop()", "desc": "Appends or removes items from array end."},
            {"id": "obj_keys", "title": "Object.keys() / values()", "desc": "Returns array of object key names or values."},
            {"id": "json_parse", "title": "JSON.parse() / stringify()", "desc": "Parses JSON text or serializes object."},
            {"id": "math_max", "title": "Math.max() / Math.min()", "desc": "Returns largest or smallest of numbers."},
            {"id": "math_random", "title": "Math.random()", "desc": "Returns pseudo-random number between 0 and 1."},
            {"id": "str_includes", "title": "String.prototype.includes()", "desc": "Checks if string contains substring."},
            {"id": "str_split", "title": "String.prototype.split()", "desc": "Splits string into array using separator."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitives", "desc": "const, let, var, number, string, boolean, null, undefined."},
            {"id": "control", "title": "Control Flow & Logic", "desc": "if, else, ternary (? :), switch, for, for...of, for...in, while."},
            {"id": "funcs", "title": "Arrow Functions & Scope", "desc": "function, => arrow syntax, closures, lexical this."},
            {"id": "objects", "title": "Objects & Prototypes", "desc": "Object literals, prototype inheritance, ES6 class syntax."},
            {"id": "async", "title": "Asynchronous JS & Promises", "desc": "Callbacks, Promise, async, await, event loop."},
            {"id": "modules", "title": "ES Modules (Import/Export)", "desc": "import, export default, named exports, CommonJS require."},
            {"id": "destructuring", "title": "Destructuring & Rest/Spread", "desc": "Array/Object destructuring, ...rest, ...spread operator."},
        ],
    },
    "typescript": {
        "functions": [
            {"id": "type_boolean", "title": "boolean", "desc": "Boolean type annotation (true or false)."},
            {"id": "type_number", "title": "number", "desc": "Numerical primitive type annotation."},
            {"id": "type_string", "title": "string", "desc": "Textual string type annotation."},
            {"id": "type_any", "title": "any / unknown", "desc": "Escape hatch any or type-safe unknown."},
            {"id": "type_never", "title": "never / void", "desc": "Unreachable type or function returning nothing."},
            {"id": "partial", "title": "Partial<T>", "desc": "Constructs type with all properties optional."},
            {"id": "required", "title": "Required<T>", "desc": "Constructs type with all properties required."},
            {"id": "readonly", "title": "Readonly<T>", "desc": "Constructs type with all properties read-only."},
            {"id": "record", "title": "Record<K, V>", "desc": "Constructs object type with keys K and value V."},
            {"id": "pick", "title": "Pick<T, K> / Omit<T, K>", "desc": "Selects or removes subset of properties K from T."},
            {"id": "returntype", "title": "ReturnType<T>", "desc": "Extracts return type of function type T."},
        ],
        "subjects": [
            {"id": "types", "title": "Type Annotations & Primitives", "desc": "number, string, boolean, explicit typing, type inference."},
            {"id": "interfaces", "title": "Interfaces & Type Aliases", "desc": "interface vs type, extending interfaces, index signatures."},
            {"id": "unions", "title": "Unions & Type Narrowing", "desc": "type A | B, typeof, instanceof, custom type predicates (is)."},
            {"id": "generics", "title": "Generics & Constraints", "desc": "Generic functions (<T>), generic interfaces, extends constraints."},
            {"id": "enums", "title": "Enums & Literal Types", "desc": "enum, const enum, string/number literal union types."},
            {"id": "classes", "title": "Classes & Access Modifiers", "desc": "public, private, protected, readonly, abstract classes."},
            {"id": "decorators", "title": "Decorators & Utility Types", "desc": "Class/method decorators, built-in TS utility type library."},
        ],
    },
    "rust": {
        "functions": [
            {"id": "type_bool", "title": "bool", "desc": "Boolean primitive type (true or false)."},
            {"id": "type_i32", "title": "i32 / i64", "desc": "Signed integer primitive types (32-bit or 64-bit)."},
            {"id": "type_u32", "title": "u32 / u64", "desc": "Unsigned integer primitive types (32-bit or 64-bit)."},
            {"id": "type_f64", "title": "f32 / f64", "desc": "Single and double precision floating-point types."},
            {"id": "type_str", "title": "str / String", "desc": "String slice (&str) and owned String buffer."},
            {"id": "type_vec", "title": "Vec<T>", "desc": "Growable heap-allocated vector collection."},
            {"id": "type_option", "title": "Option<T>", "desc": "Type representing optional value (Some or None)."},
            {"id": "type_result", "title": "Result<T, E>", "desc": "Type representing outcome (Ok or Err)."},
            {"id": "println", "title": "println!()", "desc": "Prints formatted text to stdout with newline."},
            {"id": "format", "title": "format!()", "desc": "Constructs formatted String using macro interpolation."},
            {"id": "vec_macro", "title": "vec![]", "desc": "Creates vector containing given elements."},
            {"id": "vec_push", "title": "Vec::push()", "desc": "Appends element to back of vector."},
            {"id": "string_from", "title": "String::from()", "desc": "Creates owned String from string literal."},
            {"id": "option_unwrap", "title": "Option::unwrap()", "desc": "Returns contained Some value or panics."},
            {"id": "result_expect", "title": "Result::expect()", "desc": "Returns contained Ok value or panics with message."},
            {"id": "iter_collect", "title": "Iterator::collect()", "desc": "Transforms iterator into collection."},
            {"id": "box_new", "title": "Box::new()", "desc": "Allocates memory on heap."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitives", "desc": "let, let mut, immutability, bool, i32, f64, char, str."},
            {"id": "ownership", "title": "Ownership, Borrowing & Lifetimes", "desc": "Move semantics, references (&), mutable (&mut), lifetime ('a)."},
            {"id": "control", "title": "Control Flow & Pattern Matching", "desc": "if, loop, while, for, match, if let, while let."},
            {"id": "structs", "title": "Structs & Implementations", "desc": "struct (field, tuple, unit), impl blocks, associated functions."},
            {"id": "enums", "title": "Enums & Option/Result", "desc": "enum, Option<T>, Result<T, E>, pattern matching."},
            {"id": "traits", "title": "Traits & Generics", "desc": "trait definition, impl Trait, generic functions, trait bounds."},
            {"id": "errors", "title": "Error Handling & Panic", "desc": "panic!(), recoverable errors with Result, ? operator."},
            {"id": "modules", "title": "Modules & Cargo Crates", "desc": "mod, use, pub, module hierarchy, Cargo dependencies."},
        ],
    },
    "go": {
        "functions": [
            {"id": "type_int", "title": "int / int64", "desc": "Signed integer numerical primitive types."},
            {"id": "type_bool", "title": "bool", "desc": "Boolean primitive type (true or false)."},
            {"id": "type_float", "title": "float64", "desc": "64-bit floating point real number type."},
            {"id": "type_string", "title": "string", "desc": "Immutable sequence of bytes / UTF-8 text."},
            {"id": "type_error", "title": "error", "desc": "Built-in interface type for error handling."},
            {"id": "fmt_println", "title": "fmt.Println() / Printf()", "desc": "Formatted write to standard output."},
            {"id": "make", "title": "make()", "desc": "Allocates and initializes slice, map, or channel."},
            {"id": "new", "title": "new()", "desc": "Allocates memory and returns pointer to zeroed value."},
            {"id": "append", "title": "append()", "desc": "Appends elements to end of slice."},
            {"id": "len", "title": "len() / cap()", "desc": "Returns length or capacity of collection."},
            {"id": "delete", "title": "delete()", "desc": "Deletes key entry from map."},
            {"id": "str_contains", "title": "strings.Contains()", "desc": "Reports whether substring is within string."},
            {"id": "str_atoi", "title": "strconv.Atoi()", "desc": "Converts string representation of integer to int."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitives", "desc": "var, short declaration (:=), zero values, const, type cast."},
            {"id": "control", "title": "Control Flow & Switch", "desc": "if with init, for loops (single loop construct), switch."},
            {"id": "funcs", "title": "Functions & Multiple Returns", "desc": "func, multiple returns (val, err), variadic ...T, defer."},
            {"id": "pointers", "title": "Pointers & Addresses", "desc": "Pointer types (*T), address-of (&), dereferencing (*)."},
            {"id": "structs", "title": "Structs & Methods", "desc": "type Struct struct, value vs pointer receivers (s *Struct)."},
            {"id": "interfaces", "title": "Interfaces & Duck Typing", "desc": "type Interface interface, implicit satisfaction, interface{}/any."},
            {"id": "slices", "title": "Slices & Maps", "desc": "Slicing arrays arr[1:4], make(), map access (val, ok), range."},
            {"id": "concurrency", "title": "Goroutines & Channels", "desc": "go func(), buffered/unbuffered chan, select statement."},
            {"id": "errors", "title": "Error Handling", "desc": "Explicit error return (val, err), nil checks, custom error types."},
        ],
    },
    "lua": {
        "functions": [
            {"id": "type_number", "title": "number", "desc": "Numerical data type in Lua (float/int)."},
            {"id": "type_boolean", "title": "boolean", "desc": "Boolean truth value (true or false)."},
            {"id": "type_string", "title": "string", "desc": "Byte sequence string data type."},
            {"id": "type_table", "title": "table", "desc": "Universal associative array data structure."},
            {"id": "print", "title": "print()", "desc": "Prints values to standard output."},
            {"id": "type_func", "title": "type()", "desc": "Returns string name of value data type."},
            {"id": "tostring", "title": "tostring() / tonumber()", "desc": "Converts value to string or number."},
            {"id": "table_insert", "title": "table.insert() / remove()", "desc": "Inserts or removes element from array table."},
            {"id": "table_sort", "title": "table.sort()", "desc": "Sorts elements of array table in-place."},
            {"id": "pairs", "title": "pairs() / ipairs()", "desc": "Iterators for key-value or index-value table loops."},
            {"id": "str_len", "title": "string.len() / sub()", "desc": "Returns string length or substring slice."},
            {"id": "math_abs", "title": "math.abs() / random()", "desc": "Returns absolute value or pseudo-random float."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Scope", "desc": "local vs global, dynamic typing, nil, numbers, booleans, strings."},
            {"id": "control", "title": "Control Flow & Loops", "desc": "if, elseif, else, while, repeat...until, for (numeric/generic)."},
            {"id": "funcs", "title": "Functions & First-Class Functions", "desc": "function declaration, anonymous functions, multiple returns, ..."},
            {"id": "tables", "title": "Tables as Arrays & Dictionaries", "desc": "1-indexed arrays, key-value maps, nested tables."},
            {"id": "metatables", "title": "Metatables & OOP", "desc": "setmetatable(), __index, __newindex, OOP patterns in Lua."},
            {"id": "modules", "title": "Modules & Packages", "desc": "require(), returning module tables."},
        ],
    },
    "html": {
        "functions": [
            {"id": "elem_doctype", "title": "<!DOCTYPE html>", "desc": "Declares document type as modern HTML5."},
            {"id": "elem_html", "title": "<html>", "desc": "Root element enclosing entire HTML document."},
            {"id": "elem_head", "title": "<head> / <title>", "desc": "Document metadata container and window title."},
            {"id": "elem_body", "title": "<body>", "desc": "Container for all visible web page content."},
            {"id": "elem_div", "title": "<div> / <span>", "desc": "Generic block-level and inline layout container elements."},
            {"id": "elem_headings", "title": "<h1> to <h6>", "desc": "Section heading tags ordered by hierarchy."},
            {"id": "elem_p", "title": "<p> / <br>", "desc": "Paragraph text block and line break elements."},
            {"id": "elem_a", "title": "<a>", "desc": "Anchor link element with href target attribute."},
            {"id": "elem_img", "title": "<img>", "desc": "Embedded image element with src and alt attributes."},
            {"id": "elem_lists", "title": "<ul> / <ol> / <li>", "desc": "Unordered bulleted or ordered numbered list items."},
            {"id": "elem_table", "title": "<table> / <tr> / <td>", "desc": "Tabular data container, table rows, and data cells."},
            {"id": "elem_form", "title": "<form>", "desc": "Interactive container for submitting user input controls."},
            {"id": "elem_input", "title": "<input>", "desc": "User input field (text, password, checkbox, radio, button)."},
            {"id": "elem_button", "title": "<button>", "desc": "Clickable action button element."},
        ],
        "subjects": [
            {"id": "struct", "title": "Document Structure & Setup", "desc": "DOCTYPE, html, head, body, meta tags, UTF-8 charset."},
            {"id": "semantic", "title": "Semantic HTML5 Elements", "desc": "main, nav, header, footer, section, article, layout semantics."},
            {"id": "forms", "title": "Forms & User Input Controls", "desc": "form, input types, label, select, textarea, button, validation."},
            {"id": "links", "title": "Links & Media Embeds", "desc": "Anchor tags (href, target), img, video, audio, iframe, SVG."},
            {"id": "tables", "title": "Tables & Data Display", "desc": "table, thead, tbody, tr, th, td, colspan, rowspan."},
            {"id": "attributes", "title": "Attributes & Accessibility", "desc": "id, class, style, title, data-* attributes, ARIA roles."},
        ],
    },
}


class HandbookService:
    """Language Reference Handbook service."""

    def get_catalog(self, language: str) -> Dict[str, List[Dict[str, str]]]:
        canonical = registry.canonical_name(language)
        return HANDBOOK_CATALOG.get(canonical, HANDBOOK_CATALOG["python"])

    async def generate_example_async(self, language: str, topic_id: str, topic_title: str) -> Dict[str, Any]:
        endpoint = get_chat_completions_url(config.llm_base_url)
        canonical = registry.canonical_name(language)
        config_info = registry.get_config(canonical)
        lang_name = config_info.get("name", language) if config_info else language

        prompt = (
            f"Generate a Reference Card for '{topic_title}' in {lang_name}.\n"
            f"Structure your response strictly into these four Markdown sections:\n"
            f"1. **Syntax / Signature:** Clear representation of how to invoke or write it.\n"
            f"2. **Description & Parameters:** Brief summary of parameter types and return value.\n"
            f"3. **Try It Yourself (Executable Code):** A clean, self-contained, working code snippet in ```{canonical} code blocks.\n"
            f"4. **Key Notes & Best Practices:** 2 bullet points on common pitfalls or best practices."
        )

        sys_prompt = (
            "You are an expert Documentation Assistant for TactiTerm.\n"
            "Provide clean, educational reference cards. Ensure the code example is realistic, complete, and copy-pasteable."
        )

        payload = {
            "model": config.llm_model,
            "messages": [
                {"role": "system", "content": sys_prompt},
                {"role": "user", "content": prompt},
            ],
            "temperature": 0.2,
            "max_tokens": max(config.llm_max_tokens, 4096),
        }

        headers = {"Content-Type": "application/json"}
        if config.llm_api_key and config.llm_api_key != "not-needed":
            headers["Authorization"] = f"Bearer {config.llm_api_key}"

        try:
            async with httpx.AsyncClient(timeout=config.llm_timeout, follow_redirects=True) as client:
                response = await client.post(endpoint, json=payload, headers=headers)
                response.raise_for_status()
                data = response.json()

                msg_obj = data.get("choices", [{}])[0].get("message", {})
                example_md = msg_obj.get("content") or ""
                if not example_md.strip() and msg_obj.get("reasoning_content"):
                    example_md = msg_obj.get("reasoning_content", "")
                example_md = example_md.strip()

                return {
                    "status": "success",
                    "language": lang_name,
                    "topic_title": topic_title,
                    "example_markdown": example_md,
                }
        except Exception as e:
            return {
                "status": "error",
                "message": f"Failed to generate reference card via LLM: {e}",
            }


handbook_service = HandbookService()
