import re
from typing import Tuple, Dict, Optional
from sys import exit

def parse_bbcode_style(text: str) -> Optional[Tuple[str, Dict[str, str], str]]:
    """
    Parses a string with a simple BBCode-like syntax.

    The expected format is: [tag attr1=value1 attr2="value2"]content[/tag]
    This parser handles the opening tag and the content that follows.

    Args:
        text: The input string to parse.

    Returns:
        A tuple containing:
        - The tag (str).
        - A dictionary of attributes (Dict[str, str]).
        - The content (str).
        Returns None if the string format is invalid.
    """
    # 1. Isolate the main tag block from the content by splitting at the first ']'
    try:
        tag_block_raw, content = text.split(']', 1)
    except ValueError:
        # This error occurs if ']' is not in the string, making it invalid.
        print("Error: Malformed string. No closing ']' found for the tag block.")
        return None

    # Clean up the content by removing leading/trailing whitespace
    content = content.strip()

    # 2. Validate and clean the tag block
    if not tag_block_raw.startswith('['):
        print("Error: Malformed string. Tag block does not start with '['.")
        return None
    
    # Remove the leading '[' to get the inner content of the tag
    tag_inner_content = tag_block_raw[1:].strip()

    # 3. Separate the tag from the attributes string
    parts = tag_inner_content.split(' ', 1)
    tag = parts[0]
    attributes_str = parts[1] if len(parts) > 1 else ""
    
    # 4. Parse the attributes string using a regular expression
    # This regex finds all key=value pairs.
    # - (\w+): Captures the attribute name (one or more word characters).
    # - =: Matches the literal equals sign.
    # - (?:...): A non-capturing group for the value part.
    # - "(.*?)" : Lazily captures anything inside double quotes (for values with spaces).
    # - |: Acts as an OR.
    # - ([^\s]+): Captures a sequence of non-whitespace characters (for unquoted values).
    # The findall will return a list of tuples, e.g., [('attr', 'val'), ('attr2', '"val2"')]
    # We need to clean the quotes from the values.
    
    # A more robust regex to handle both cases cleanly
    # (\w+)=       -> Group 1: the key
    # (?:          -> Start of non-capturing group for the value
    #   "([^"]*)"  -> Group 2: a quoted value (captures content inside quotes)
    #   |          -> OR
    #   (\S+)      -> Group 3: an unquoted value (any non-space characters)
    # )            -> End of non-capturing group
    attribute_pattern = re.compile(r'(\w+)=(?:"([^"]*)"|(\S+))')
    
    attributes = {}
    if attributes_str:
        matches = attribute_pattern.findall(attributes_str)
        for key, quoted_value, unquoted_value in matches:
            # The value will be in either quoted_value or unquoted_value
            attributes[key] = quoted_value if quoted_value else unquoted_value

    return tag, attributes, content

# --- Example Usage ---
from sys import argv

with open(argv[1]) as fd:
    data = fd.read()

print(data[1])
for line in data.splitlines():
    parsed = parse_bbcode_style(line.strip())
    if not parsed:
        exit(1)
    # print(parsed)

# from ikml_doc import IKML_Document

# doc = IKML_Document(data=data)
