from .exc import ConverterError

class InstanceXMixin:
    def process_instance_x(self, lws, line, eol, annot, in_sub):
        """
        Process X instance (subcircuit).
        """
        name = annot["name"]
        parts = annot["words"]
        mod_index = annot["mod_index"]
        model = annot["mod_name"]
        
        if model is None:
            raise ConverterError(line+"\nModel not found.")
        
        terminals = self.process_terminals(parts[:mod_index])
        params = parts[(mod_index+1):]
        
        # Process parameters, do not handle m (keep its name unchanged)
        psplit = self.process_instance_params(params, "x", handle_m=False, in_sub=in_sub)
        
        # Do not use output model name from output_mod_name. 
        # Decide based on original_case_subckt value. 
        if self.cfg.get("original_case_subckt", False):
            output_model = annot["orig_mod_name"]
        else:
            output_model = annot["mod_name"]

        txt = lws + annot["output_name"] + " (" + (" ".join(terminals))+") "+output_model+" "

        if len(psplit)>0:
            fmted, need_split, split = self.format_params(psplit, len(txt))
            if need_split or split:
                fmted = self.indent(fmted, len(lws)+2)
                txt += "(" + eol + "\n" + fmted
                txt += "\n" + lws + ")"
            else:
                txt += " " + fmted
        
        return txt
