"""W3Schools-Style 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": "print", "title": "print()", "desc": "Prints specified objects to standard output."},
            {"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": "input", "title": "input()", "desc": "Reads line from standard input as string."},
            {"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": "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."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitive Types", "desc": "int, float, bool, str, and dynamic typing."},
            {"id": "control", "title": "Control Flow & Loops", "desc": "if, elif, else, for, while, break, continue."},
            {"id": "funcs", "title": "Functions & Type Hints", "desc": "def, return, lambda, *args, **kwargs."},
            {"id": "collections", "title": "Lists, Dicts & Sets", "desc": "Comprehensions, operations, set math."},
            {"id": "errors", "title": "Exception Handling", "desc": "try, except, else, finally, raise."},
            {"id": "oop", "title": "Classes & OOP", "desc": "class, __init__, self, inheritance."},
        ],
    },
    "rust": {
        "functions": [
            {"id": "type_bool", "title": "bool", "desc": "Boolean primitive type (true or false)."},
            {"id": "type_i32", "title": "i32 / i64", "desc": "Signed integer types (32-bit or 64-bit)."},
            {"id": "type_u32", "title": "u32 / u64", "desc": "Unsigned integer types (32-bit or 64-bit)."},
            {"id": "type_f64", "title": "f32 / f64", "desc": "Floating-point primitive types."},
            {"id": "type_str", "title": "str / String", "desc": "String slice (&str) and owned String type."},
            {"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, bool, i32, f64, char, str."},
            {"id": "ownership", "title": "Ownership & Borrowing", "desc": "Move semantics, references (&), mutable (&mut)."},
            {"id": "control", "title": "Control Flow & Match", "desc": "if, loop, while, for, match pattern matching."},
            {"id": "structs", "title": "Structs & Enums", "desc": "struct, impl, enum, Option, Result."},
            {"id": "traits", "title": "Traits & Generics", "desc": "trait definition, generic type signatures."},
        ],
    },
    "cpp": {
        "functions": [
            {"id": "type_int", "title": "int", "desc": "Signed 32-bit integer primitive type."},
            {"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 string object."},
            {"id": "type_vector", "title": "std::vector<T>", "desc": "Dynamic array sequence container."},
            {"id": "std_cout", "title": "std::cout / std::cin", "desc": "Standard input and output streams."},
            {"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 unique pointer object."},
            {"id": "make_shared", "title": "std::make_shared()", "desc": "Constructs shared pointer object."},
        ],
        "subjects": [
            {"id": "vars", "title": "Primitive Data Types", "desc": "int, float, double, bool, char, void, const, auto."},
            {"id": "control", "title": "Control Flow & Loops", "desc": "if, else, for, while, do while, switch."},
            {"id": "pointers", "title": "Pointers & References", "desc": "Raw pointers (*), references (&), nullptr."},
            {"id": "classes", "title": "Classes & OOP", "desc": "class, struct, public, private, constructors."},
        ],
    },
    "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_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 chan."},
            {"id": "append", "title": "append()", "desc": "Appends elements to slice."},
            {"id": "len", "title": "len() / cap()", "desc": "Returns length or capacity of collection."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitives", "desc": "var, :=, int, float64, bool, string, const."},
            {"id": "control", "title": "Control Flow & Switch", "desc": "if with init, for loops, switch, select."},
            {"id": "structs", "title": "Structs & Interfaces", "desc": "type struct, methods, interface."},
            {"id": "goroutines", "title": "Goroutines & Channels", "desc": "go func(), chan, select statement."},
        ],
    },
    "javascript": {
        "functions": [
            {"id": "type_boolean", "title": "boolean / bool", "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": "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."},
            {"id": "arr_reduce", "title": "Array.prototype.reduce()", "desc": "Executes reducer function on elements."},
            {"id": "obj_keys", "title": "Object.keys()", "desc": "Returns array of object key names."},
            {"id": "json_parse", "title": "JSON.parse()", "desc": "Parses JSON string into object."},
            {"id": "fetch", "title": "fetch()", "desc": "Asynchronously fetches network resource."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitives", "desc": "const, let, var, number, string, boolean, null."},
            {"id": "control", "title": "Control Flow & Logic", "desc": "if, else, ternary, for...of, for...in."},
            {"id": "funcs", "title": "Arrow Functions & Async", "desc": "function, =>, async, await, Promises."},
        ],
    },
    "typescript": {
        "functions": [
            {"id": "type_boolean", "title": "boolean / bool", "desc": "Boolean type annotation (true or false)."},
            {"id": "type_number", "title": "number / int", "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": "record", "title": "Record<K, V>", "desc": "Constructs object type with keys K and value V."},
            {"id": "partial", "title": "Partial<T>", "desc": "Constructs type with all properties optional."},
            {"id": "readonly", "title": "Readonly<T>", "desc": "Constructs type with all properties read-only."},
        ],
        "subjects": [
            {"id": "types", "title": "Type Annotations & Primitive Types", "desc": "number, string, boolean, interface, type."},
            {"id": "unions", "title": "Unions & Narrowing", "desc": "Type A | Type B, typeof, instanceof."},
        ],
    },
    "java": {
        "functions": [
            {"id": "type_int", "title": "int / long", "desc": "Primitive integer data types."},
            {"id": "type_boolean", "title": "boolean / bool", "desc": "Primitive boolean true or false."},
            {"id": "type_double", "title": "float / double", "desc": "Primitive floating point data types."},
            {"id": "type_string", "title": "String", "desc": "Java String object class."},
            {"id": "sys_out", "title": "System.out.println()", "desc": "Writes formatted text to standard output."},
            {"id": "list_add", "title": "List.add()", "desc": "Appends element to Java List collection."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Primitives", "desc": "int, double, boolean, String, char, float."},
            {"id": "control", "title": "Control Flow", "desc": "if, else, for, while, switch."},
        ],
    },
    "csharp": {
        "functions": [
            {"id": "type_int", "title": "int / long", "desc": "Signed integer primitive types."},
            {"id": "type_bool", "title": "bool", "desc": "Boolean primitive type (true or false)."},
            {"id": "type_string", "title": "string", "desc": "UTF-16 text string type."},
            {"id": "console_write", "title": "Console.WriteLine()", "desc": "Writes line terminator to stdout."},
            {"id": "list_add", "title": "List<T>.Add()", "desc": "Adds item to List collection."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Types", "desc": "int, bool, string, double, float, var."},
            {"id": "control", "title": "Control Flow & OOP", "desc": "if, else, foreach, class, struct, record."},
        ],
    },
    "lua": {
        "functions": [
            {"id": "type_number", "title": "number / int", "desc": "Numerical data type."},
            {"id": "type_boolean", "title": "boolean / bool", "desc": "Boolean truth value (true or false)."},
            {"id": "type_string", "title": "string", "desc": "Byte sequence string type."},
            {"id": "print", "title": "print()", "desc": "Prints values to standard output."},
        ],
        "subjects": [
            {"id": "vars", "title": "Variables & Types", "desc": "local, number, string, boolean, nil, table."},
        ],
    },
    "html": {
        "functions": [
            {"id": "elem_doctype", "title": "<!DOCTYPE html>", "desc": "Declares document type as HTML5."},
            {"id": "elem_html", "title": "<html>", "desc": "Root element of HTML document."},
            {"id": "elem_body", "title": "<body>", "desc": "Container for all visible web page contents."},
            {"id": "elem_div", "title": "<div> / <span>", "desc": "Block or inline layout container elements."},
        ],
        "subjects": [
            {"id": "struct", "title": "Document Structure & Elements", "desc": "DOCTYPE, html, head, body, div, p, a, input."},
        ],
    },
}


class HandbookService:
    """W3Schools-Style 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 W3Schools-Style 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 W3Schools-Style 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": 900,
        }

        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()

                example_md = (
                    data.get("choices", [{}])[0]
                    .get("message", {})
                    .get("content", "")
                    .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 W3Schools reference card via LLM: {e}",
            }


handbook_service = HandbookService()
