# From https://raw.githubusercontent.com/microsoft/pyright/main/packages/pyright-internal/src/localization/package.nls.en-us.json
import re
import textwrap
from typing import NamedTuple, Dict, List

import parse

from nicepyright.utils import con


def _get_message_parsers() -> Dict[str, Dict[str, parse.Parser]]:
    raw_messages = {
        "Diagnostic": {
            "annotatedParamCountMismatch": "Parameter annotation count mismatch: expected {expected} but received {received}",
            "annotatedTypeArgMissing": 'Expected one type argument and one or more annotations for "Annotated"',
            "annotationFormatString": "Type annotations cannot use format string literals (f-strings)",
            "annotationNotSupported": "Type annotation not supported for this statement",
            "annotationSpansStrings": "Type annotations cannot span multiple string literals",
            "annotationStringEscape": "Type annotations cannot contain escape characters",
            "argAssignment": 'Argument of type "{argType}" cannot be assigned to parameter of type "{paramType}"',
            "argAssignmentFunction": 'Argument of type "{argType}" cannot be assigned to parameter of type "{paramType}" in function "{functionName}"',
            "argAssignmentParam": 'Argument of type "{argType}" cannot be assigned to parameter "{paramName}" of type "{paramType}"',
            "argAssignmentParamFunction": 'Argument of type "{argType}" cannot be assigned to parameter "{paramName}" of type "{paramType}" in function "{functionName}"',
            "argMissingForParam": "Argument missing for parameter {name}",
            "argMissingForParams": "Arguments missing for parameters {names}",
            "argMorePositionalExpectedCount": "Expected {expected} more positional arguments",
            "argMorePositionalExpectedOne": "Expected 1 more positional argument",
            "argPositional": "Expected positional argument",
            "argPositionalExpectedCount": "Expected {expected} positional arguments",
            "argPositionalExpectedOne": "Expected 1 positional argument",
            "argTypePartiallyUnknown": "Argument type is partially unknown",
            "argTypeUnknown": "Argument type is unknown",
            "assertAlwaysTrue": "Assert expression always evaluates to true",
            "assertTypeArgs": '"assert_type" expects two positional arguments',
            "assertTypeTypeMismatch": '"assert_type" mismatch: expected "{expected}" but received "{received}"',
            "assignmentExprContext": "Assignment expression must be within module, function or lambda",
            "assignmentExprComprehension": 'Assignment expression target "{name}" cannot use same name as comprehension for target',
            "assignmentInProtocol": "Instance or class variables within a Protocol class must be explicitly declared within the class body",
            "assignmentExprInSubscript": "Assignment expressions within a subscript are supported only in Python 3.10 and newer",
            "assignmentTargetExpr": "Expression cannot be assignment target",
            "asyncNotInAsyncFunction": 'Use of "async" not allowed outside of async function',
            "awaitIllegal": 'Use of "await" requires Python 3.5 or newer',
            "awaitNotInAsync": '"await" allowed only within async function',
            "backticksIllegal": "Expressions surrounded by backticks are not supported in Python 3.x; use repr instead",
            "baseClassCircular": "Class cannot derive from itself",
            "baseClassFinal": 'Base class "{type}" is marked final and cannot be subclassed',
            "baseClassInvalid": "Argument to class must be a base class",
            "baseClassMethodTypeIncompatible": 'Base classes for class "{classType}" define method "{name}" in incompatible way',
            "baseClassVariableTypeIncompatible": 'Base classes for class "{classType}" define variable "{name}" in incompatible way',
            "baseClassUnknown": "Base class type is unknown, obscuring type of derived class",
            "bindTypeMismatch": 'Could not bind method "{methodName}" because "{type}" is not assignable to parameter "{paramName}"',
            "breakOutsideLoop": '"break" can be used only within a loop',
            "callableExtraArgs": 'Expected only two type arguments to "Callable"',
            "callableFirstArg": 'Expected parameter type list or "..."',
            "callableSecondArg": 'Expected return type as second type argument for "Callable"',
            "casePatternIsIrrefutable": "Irrefutable pattern is allowed only for the last case statement",
            "classAlreadySpecialized": 'Type "{type}" is already specialized',
            "classDecoratorTypeUnknown": "Untyped class decorator obscures type of class; ignoring decorator",
            "classDefinitionCycle": 'Class definition for "{name}" depends on itself',
            "classGetItemClsParam": '__class_getitem__ override should take a "cls" parameter',
            "classMethodClsParam": 'Class methods should take a "cls" parameter',
            "classNotRuntimeSubscriptable": 'Subscript for class "{name}" will generate runtime exception; enclose type annotation in quotes',
            "classPatternBuiltInArgCount": "Class pattern accepts at most 1 positional sub-pattern",
            "classPatternBuiltInArgPositional": "Class pattern accepts only positional sub-pattern",
            "classPatternTypeAlias": '"{type}" cannot be used in a class pattern because it is a specialized type alias',
            "classTypeParametersIllegal": "Class type parameter syntax requires Python 3.12 or newer",
            "classVarNotAllowed": '"ClassVar" is not allowed in this context',
            "classVarFirstArgMissing": 'Expected a type argument after "ClassVar"',
            "classVarOverridesInstanceVar": 'Class variable "{name}" overrides instance variable of same name in class "{className}"',
            "classVarTooManyArgs": 'Expected only one type argument after "ClassVar"',
            "classVarWithTypeVar": '"ClassVar" type cannot include type variables',
            "clsSelfParamTypeMismatch": 'Type of parameter "{name}" must be a supertype of its class "{classType}"',
            "codeTooComplexToAnalyze": "Code is too complex to analyze; reduce complexity by refactoring into subroutines or reducing conditional code paths",
            "collectionAliasInstantiation": 'Type "{type}" cannot be instantiated, use "{alias}" instead',
            "comparisonAlwaysFalse": 'Condition will always evaluate to False since the types "{leftType}" and "{rightType}" have no overlap',
            "comparisonAlwaysTrue": 'Condition will always evaluate to True since the types "{leftType}" and "{rightType}" have no overlap',
            "comprehensionInDict": "Comprehension cannot be used with other dictionary entries",
            "comprehensionInSet": "Comprehension cannot be used with other set entries",
            "concatenateParamSpecMissing": 'Last type argument for "Concatenate" must be a ParamSpec',
            "concatenateTypeArgsMissing": '"Concatenate" requires at least two type arguments',
            "constantRedefinition": '"{name}" is constant (because it is uppercase) and cannot be redefined',
            "constructorParametersMismatch": 'Mismatch between signature of __new__ and __init__ in class "{classType}"',
            "containmentAlwaysFalse": 'Expression will always evaluate to False since the types "{leftType}" and "{rightType}" have no overlap',
            "containmentAlwaysTrue": 'Expression will always evaluate to True since the types "{leftType}" and "{rightType}" have no overlap',
            "continueInFinally": '"continue" cannot be used within a finally clause',
            "continueOutsideLoop": '"continue" can be used only within a loop',
            "constructorNoArgs": 'Expected no arguments to "{type}" constructor',
            "dataClassBaseClassFrozen": "A non-frozen class cannot inherit from a class that is frozen",
            "dataClassBaseClassNotFrozen": "A frozen class cannot inherit from a class that is not frozen",
            "dataClassFieldWithDefault": "Fields without default values cannot appear after fields with default values",
            "dataClassFieldWithoutAnnotation": "Dataclass field without type annotation will cause runtime exception",
            "dataClassPostInitParamCount": "Dataclass __post_init__ incorrect parameter count; number of InitVar fields is {expected}",
            "dataClassPostInitType": 'Dataclass __post_init__ method parameter type mismatch for field "{fieldName}"',
            "dataClassSlotsOverwrite": "__slots__ is already defined in class",
            "dataClassTransformExpectedBoolLiteral": "Expected expression that statically evaluates to True or False",
            "dataClassTransformFieldSpecifier": 'Expected tuple of classes or functions but received type "{type}"',
            "dataClassTransformPositionalParam": 'All arguments to "dataclass_transform" must be keyword arguments',
            "dataClassTransformUnknownArgument": 'Argument "{name}" is not supported by dataclass_transform',
            "declaredReturnTypePartiallyUnknown": 'Declared return type, "{returnType}", is partially unknown',
            "declaredReturnTypeUnknown": "Declared return type is unknown",
            "defaultValueContainsCall": "Function calls and mutable objects not allowed within parameter default value expression",
            "defaultValueNotAllowed": 'Parameter with "*" or "**" cannot have default value',
            "deprecatedType": 'This type is deprecated as of Python {version}; use "{replacement}" instead',
            "delTargetExpr": "Expression cannot be deleted",
            "dictExpandIllegalInComprehension": "Dictionary expansion not allowed in comprehension",
            "dictInAnnotation": "Dictionary expression not allowed in type annotation",
            "dictKeyValuePairs": "Dictionary entries must contain key/value pairs",
            "dictUnpackIsNotMapping": "Expected mapping for dictionary unpack operator",
            "dunderAllSymbolNotPresent": '"{name}" is specified in __all__ but is not present in module',
            "duplicateArgsParam": 'Only one "*" parameter allowed',
            "duplicateBaseClass": "Duplicate base class not allowed",
            "duplicateCatchAll": "Only one catch-all except clause allowed",
            "duplicateEnumMember": 'Enum member "{name}" is already declared',
            "duplicateGenericAndProtocolBase": "Only one Generic[...] or Protocol[...] base class allowed",
            "duplicateImport": '"{importName}" is imported more than once',
            "duplicateKwargsParam": 'Only one "**" parameter allowed',
            "duplicateKeywordOnly": 'Only one "*" separator allowed',
            "duplicateParam": 'Duplicate parameter "{name}"',
            "duplicateCapturePatternTarget": 'Capture target "{name}" cannot appear more than once within the same pattern',
            "duplicateStarPattern": 'Only one "*" pattern allowed in a pattern sequence',
            "duplicateStarStarPattern": 'Only one "**" entry allowed',
            "duplicatePositionOnly": 'Only one "/" parameter allowed',
            "duplicateUnpack": "Only one unpack operation allowed in list",
            "ellipsisContext": '"..." not allowed in this context',
            "ellipsisSecondArg": '"..." allowed only as the second of two arguments',
            "enumClassOverride": 'Enum class "{name}" is final and cannot be subclassed',
            "exceptionGroupIncompatible": 'Exception group syntax ("except*") requires Python 3.11 or newer',
            "exceptionTypeIncorrect": '"{type}" does not derive from BaseException',
            "exceptionTypeNotClass": '"{type}" is not valid exception class',
            "exceptionTypeNotInstantiable": 'Constructor for exception type "{type}" requires one or more arguments',
            "expectedAfterDecorator": "Expected function or class declaration after decorator",
            "expectedArrow": 'Expected "->" followed by return type annotation',
            "expectedAsAfterException": 'Expected "as" after exception type',
            "expectedAssignRightHandExpr": 'Expected expression to the right of "="',
            "expectedBinaryRightHandExpr": "Expected expression to the right of operator",
            "expectedBoolLiteral": "Expected True or False",
            "expectedCase": 'Expected "case" statement',
            "expectedClassName": "Expected class name",
            "expectedCloseBrace": '"{" was not closed',
            "expectedCloseBracket": '"[" was not closed',
            "expectedCloseParen": '"(" was not closed',
            "expectedColon": 'Expected ":"',
            "expectedComplexNumberLiteral": "Expected complex number literal for pattern matching",
            "expectedDecoratorExpr": "Expression form not supported for decorator prior to Python 3.9",
            "expectedDecoratorName": "Expected decorator name",
            "expectedDecoratorNewline": "Expected new line at end of decorator",
            "expectedDelExpr": 'Expected expression after "del"',
            "expectedElse": 'Expected "else"',
            "expectedEquals": 'Expected "="',
            "expectedExceptionClass": "Invalid exception class or object",
            "expectedExceptionObj": "Expected exception object, exception class or None",
            "expectedExpr": "Expected expression",
            "expectedIdentifier": "Expected identifier",
            "expectedImport": 'Expected "import"',
            "expectedImportAlias": 'Expected symbol after "as"',
            "expectedImportSymbols": "Expected one or more symbol names after import",
            "expectedIndentedBlock": "Expected indented block",
            "expectedInExpr": 'Expected expression after "in"',
            "expectedIn": 'Expected "in"',
            "expectedFunctionAfterAsync": 'Expected function definition after "async"',
            "expectedFunctionName": 'Expected function name after "def"',
            "expectedMemberName": 'Expected member name after "."',
            "expectedModuleName": "Expected module name",
            "expectedNameAfterAs": 'Expected symbol name after "as"',
            "expectedNamedParameter": 'Keyword parameter must follow "*"',
            "expectedNewline": "Expected newline",
            "expectedNewlineOrSemicolon": "Statements must be separated by newlines or semicolons",
            "expectedOpenParen": 'Expected "("',
            "expectedParamName": "Expected parameter name",
            "expectedPatternExpr": "Expected pattern expression",
            "expectedPatternSubjectExpr": "Expected pattern subject expression",
            "expectedPatternValue": 'Expected pattern value expression of the form "a.b"',
            "expectedReturnExpr": 'Expected expression after "return"',
            "expectedSliceIndex": "Expected index or slice expression",
            "expectedTypeNotString": "Expected type but received a string literal",
            "expectedTypeParameterName": "Expected type parameter name",
            "expectedYieldExpr": "Expected expression in yield statement",
            "finalClassIsAbstract": 'Class "{type}" is marked final and must implement all abstract methods',
            "finalContext": '"Final" not allowed in this context',
            "finalMethodOverride": 'Method "{name}" cannot override final method defined in class "{className}"',
            "finalReassigned": '"{name}" is declared as Final and cannot be reassigned',
            "finalRedeclaration": '"{name}" was previously declared as Final',
            "finalRedeclarationBySubclass": '"{name}" cannot be redeclared because parent class "{className}" declares it as Final',
            "finalTooManyArgs": 'Expected a single type argument after "Final"',
            "finalUnassigned": '"{name}" is declared Final, but value is not assigned',
            "formatStringBrace": "Single close brace not allowed within f-string literal; use double close brace",
            "formatStringBytes": "Format string literals (f-strings) cannot be binary",
            "formatStringEscape": "Escape sequence (backslash) not allowed in expression portion of f-string",
            "formatStringInPattern": "Format string not allowed in pattern",
            "formatStringUnicode": "Format string literals (f-strings) cannot be unicode",
            "formatStringIllegal": "Format string literals (f-strings) require Python 3.6 or newer",
            "formatStringUnterminated": "Unterminated expression in f-string; missing close brace",
            "functionDecoratorTypeUnknown": "Untyped function decorator obscures type of function; ignoring decorator",
            "functionInConditionalExpression": "Conditional expression references function which always evaluates to True",
            "functionTypeParametersIllegal": "Function type parameter syntax requires Python 3.12 or newer",
            "futureImportLocationNotAllowed": "Imports from __future__ must be at the beginning of the file",
            "generatorAsyncReturnType": 'Return type of async generator function must be "AsyncGenerator" or "AsyncIterable"',
            "generatorNotParenthesized": "Generator expressions must be parenthesized if not sole argument",
            "generatorSyncReturnType": 'Return type of generator function must be "Generator" or "Iterable"',
            "genericBaseClassNotAllowed": '"Generic" base class cannot be used with type parameter syntax',
            "genericClassAssigned": "Generic class type cannot be assigned",
            "genericClassDeleted": "Generic class type cannot be deleted",
            "genericNotAllowed": '"Generic" is not valid in this context',
            "genericTypeAliasBoundTypeVar": "Generic type alias within class cannot use bound type variables {names}",
            "genericTypeArgMissing": '"Generic" requires at least one type argument',
            "genericTypeArgTypeVar": 'Type argument for "Generic" must be a type variable',
            "genericTypeArgUnique": 'Type arguments for "Generic" must be unique',
            "globalReassignment": '"{name}" is assigned before global declaration',
            "globalRedefinition": '"{name}" was already declared global',
            "implicitStringConcat": "Implicit string concatenation not allowed",
            "importCycleDetected": "Cycle detected in import chain",
            "importDepthExceeded": "Import chain depth exceeded {depth}",
            "importResolveFailure": 'Import "{importName}" could not be resolved',
            "importSourceResolveFailure": 'Import "{importName}" could not be resolved from source',
            "importSymbolUnknown": '"{name}" is unknown import symbol',
            "incompatibleMethodOverride": 'Method "{name}" overrides class "{className}" in an incompatible manner',
            "inconsistentIndent": "Unindent amount does not match previous indent",
            "initMustReturnNone": 'Return type of "__init__" must be None',
            "inconsistentTabs": "Inconsistent use of tabs and spaces in indentation",
            "initSubclassClsParam": '__init_subclass__ override should take a "cls" parameter',
            "instanceMethodSelfParam": 'Instance methods should take a "self" parameter',
            "instanceVarOverridesClassVar": 'Instance variable "{name}" overrides class variable of same name in class "{className}"',
            "instantiateAbstract": 'Cannot instantiate abstract class "{type}"',
            "instantiateProtocol": 'Cannot instantiate protocol class "{type}"',
            "internalBindError": 'An internal error occurred while binding file "{file}": {message}',
            "internalParseError": 'An internal error occurred while parsing file "{file}": {message}',
            "internalTypeCheckingError": 'An internal error occurred while type checking file "{file}": {message}',
            "invalidIdentifierChar": "Invalid character in identifier",
            "invalidStubStatement": "Statement is meaningless within a type stub file",
            "invalidTokenChars": 'Invalid character "{text}" in token',
            "isInstanceInvalidType": 'Second argument to "isinstance" must be a class or tuple of classes',
            "isSubclassInvalidType": 'Second argument to "issubclass" must be a class or tuple of classes',
            "keyValueInSet": "Key/value pairs are not allowed within a set",
            "keywordArgInTypeArgument": "Keyword arguments cannot be used in type argument lists",
            "keywordOnlyAfterArgs": 'Keyword-only argument separator not allowed after "*" parameter',
            "keywordParameterMissing": 'One or more keyword parameters must follow "*" parameter',
            "keywordSubscriptIllegal": "Keyword arguments within subscripts are not supported",
            "lambdaReturnTypeUnknown": "Return type of lambda is unknown",
            "lambdaReturnTypePartiallyUnknown": 'Return type of lambda, "{returnType}", is partially unknown',
            "listAssignmentMismatch": 'Expression with type "{type}" cannot be assigned to target list',
            "listInAnnotation": "List expression not allowed in type annotation",
            "literalUnsupportedType": 'Type arguments for "Literal" must be None, a literal value (int, bool, str, or bytes), or an enum value',
            "literalEmptyArgs": 'Expected one or more type arguments after "Literal"',
            "literalNotCallable": "Literal type cannot be instantiated",
            "matchIncompatible": "Match statements require Python 3.10 or newer",
            "matchIsNotExhaustive": "Cases within match statement do not exhaustively handle all values",
            "maxParseDepthExceeded": "Maximum parse depth exceeded; break expression into smaller sub-expressions",
            "memberAccess": 'Cannot access member "{name}" for type "{type}"',
            "memberDelete": 'Cannot delete member "{name}" for type "{type}"',
            "memberSet": 'Cannot assign member "{name}" for type "{type}"',
            "metaclassConflict": "The metaclass of a derived class must be a subclass of the metaclasses of all its base classes",
            "metaclassDuplicate": "Only one metaclass can be provided",
            "metaclassIsGeneric": "Metaclass cannot be generic",
            "methodNotDefined": '"{name}" method not defined',
            "methodNotDefinedOnType": '"{name}" method not defined on type "{type}"',
            "methodOrdering": "Cannot create consistent method ordering",
            "methodOverridden": '"{name}" overrides method of same name in class "{className}" with incompatible type "{type}"',
            "methodReturnsNonObject": '"{name}" method does not return an object',
            "missingProtocolMembers": "Class derives from one or more protocol classes but does not implement all required members",
            "missingSuperCall": 'Method "{methodName}" does not call the method of the same name in parent class',
            "moduleAsType": "Module cannot be used as a type",
            "moduleNotCallable": "Module is not callable",
            "moduleUnknownMember": '"{name}" is not a known member of module',
            "namedExceptAfterCatchAll": "A named except clause cannot appear after catch-all except clause",
            "namedParamAfterParamSpecArgs": 'Keyword parameter "{name}" cannot appear in signature after ParamSpec args parameter',
            "namedTupleEmptyName": "Names within a named tuple cannot be empty",
            "namedTupleMultipleInheritance": "Multiple inheritance with NamedTuple is not supported",
            "namedTupleFirstArg": "Expected named tuple class name as first argument",
            "namedTupleNameType": "Expected two-entry tuple specifying entry name and type",
            "namedTupleNameUnique": "Names within a named tuple must be unique",
            "namedTupleNoTypes": '"namedtuple" provides no types for tuple entries; use "NamedTuple" instead',
            "namedTupleSecondArg": "Expected named tuple entry list as second argument",
            "newClsParam": '__new__ override should take a "cls" parameter',
            "newTypeBadName": "The first argument to NewType must be a string literal",
            "newTypeLiteral": "NewType cannot be used with Literal type",
            "newTypeNotAClass": "Expected class as second argument to NewType",
            "newTypeParamCount": "NewType requires two positional arguments",
            "newTypeProtocolClass": "NewType cannot be used with protocol class",
            "nonDefaultAfterDefault": "Non-default argument follows default argument",
            "noneNotCallable": 'Object of type "None" cannot be called',
            "noneNotIterable": 'Object of type "None" cannot be used as iterable value',
            "noneOperator": 'Operator "{operator}" not supported for "None"',
            "noneNotSubscriptable": 'Object of type "None" is not subscriptable',
            "noneNotUsableWith": 'Object of type "None" cannot be used with "with"',
            "noneUnknownMember": '"{name}" is not a known member of "None"',
            "nonLocalNoBinding": 'No binding for nonlocal "{name}" found',
            "nonLocalReassignment": '"{name}" is assigned before nonlocal declaration',
            "nonLocalRedefinition": '"{name}" was already declared nonlocal',
            "nonLocalInModule": "Nonlocal declaration not allowed at module level",
            "noOverload": 'No overloads for "{name}" match the provided arguments',
            "noReturnContainsReturn": 'Function with declared return type "NoReturn" cannot include a return statement',
            "noReturnContainsYield": 'Function with declared return type "NoReturn" cannot include a yield statement',
            "noReturnReturnsNone": 'Function with declared type of "NoReturn" cannot return "None"',
            "notRequiredArgCount": 'Expected a single type argument after "NotRequired"',
            "notRequiredNotInTypedDict": '"NotRequired" is not allowed in this context',
            "objectNotCallable": 'Object of type "{type}" is not callable',
            "obscuredClassDeclaration": 'Class declaration "{name}" is obscured by a declaration of the same name',
            "obscuredFunctionDeclaration": 'Function declaration "{name}" is obscured by a declaration of the same name',
            "obscuredMethodDeclaration": 'Method declaration "{name}" is obscured by a declaration of the same name',
            "obscuredParameterDeclaration": 'Parameter declaration "{name}" is obscured by a declaration of the same name',
            "obscuredTypeAliasDeclaration": 'Type alias declaration "{name}" is obscured by a declaration of the same name',
            "obscuredVariableDeclaration": 'Declaration "{name}" is obscured by a declaration of the same name',
            "operatorLessOrGreaterDeprecated": 'Operator "<>" is not supported in Python 3; use "!=" instead',
            "optionalExtraArgs": 'Expected one type argument after "Optional"',
            "orPatternIrrefutable": 'Irrefutable pattern allowed only as the last subpattern in an "or" pattern',
            "orPatternMissingName": 'All subpatterns within an "or" pattern must target the same names',
            "overlappingOverload": 'Overload {obscured} for "{name}" will never be used because its parameters overlap overload {obscuredBy}',
            "overloadAbstractMismatch": "Overloaded methods must all be abstract or not",
            "overloadImplementationMismatch": "Overloaded implementation is not consistent with signature of overload {index}",
            "overloadReturnTypeMismatch": 'Overload {prevIndex} for "{name}" overlaps overload {newIndex} and returns an incompatible type',
            "overloadWithImplementation": '"{name}" is marked as overload, but it includes an implementation',
            "overloadWithoutImplementation": '"{name}" is marked as overload, but no implementation is provided',
            "overrideNotFound": 'Method "{name}" is marked as override, but no base method of same name is present',
            "paramAfterKwargsParam": 'Parameter cannot follow "**" parameter',
            "paramAlreadyAssigned": 'Parameter "{name}" is already assigned',
            "paramAnnotationMissing": 'Type annotation is missing for parameter "{name}"',
            "paramNameMissing": 'No parameter named "{name}"',
            "paramSpecArgsKwargsUsage": '"args" and "kwargs" members of ParamSpec must both appear within a function signature',
            "paramSpecArgsMissing": 'Arguments for ParamSpec "{type}" are missing',
            "paramSpecArgsUsage": '"args" member of ParamSpec is valid only when used with *args parameter',
            "paramSpecAssignedName": 'ParamSpec must be assigned to a variable named "{name}"',
            "paramSpecContext": "ParamSpec not allowed in this context",
            "paramSpecDefaultNotTuple": "Expected ellipsis, a tuple expression, or ParamSpec for default value of ParamSpec",
            "paramSpecFirstArg": "Expected name of ParamSpec as first argument",
            "paramSpecKwargsUsage": '"kwargs" member of ParamSpec is valid only when used with **kwargs parameter',
            "paramSpecNotBound": 'Param spec "{type}" has no bound value',
            "paramSpecNotUsedByOuterScope": 'ParamSpec "{name}" has no meaning in this context',
            "paramSpecScopedToReturnType": 'ParamSpec "{name}" is scoped to a callable within the return type and cannot be referenced in the function body',
            "paramSpecUnknownArg": "ParamSpec does not support more than one argument",
            "paramSpecUnknownMember": '"{name}" is not a known member of ParamSpec',
            "paramSpecUnknownParam": '"{name}" is unknown parameter to ParamSpec',
            "paramAssignmentMismatch": 'Expression of type "{sourceType}" cannot be assigned to parameter of type "{paramType}"',
            "paramTypeCovariant": "Covariant type variable cannot be used in parameter type",
            "paramTypeUnknown": 'Type of parameter "{paramName}" is unknown',
            "paramTypePartiallyUnknown": 'Type of parameter "{paramName}" is partially unknown',
            "parenthesizedContextManagerIllegal": 'Parentheses within "with" statement requires Python 3.9 or newer',
            "positionArgAfterNamedArg": "Positional argument cannot appear after keyword arguments",
            "privateImportFromPyTypedModule": '"{name}" is not exported from module "{module}"',
            "positionOnlyAfterArgs": 'Position-only argument separator not allowed after "*" parameter',
            "positionOnlyAfterKeywordOnly": '"/" parameter must appear before "*" parameter',
            "positionOnlyIncompatible": "Position-only argument separator requires Python 3.8 or newer",
            "positionOnlyFirstParam": "Position-only argument separator not allowed as first parameter",
            "privateUsedOutsideOfClass": '"{name}" is private and used outside of the class in which it is declared',
            "privateUsedOutsideOfModule": '"{name}" is private and used outside of the module in which it is declared',
            "propertyOverridden": '"{name}" incorrectly overrides property of same name in class "{className}"',
            "propertyStaticMethod": "Static methods not allowed for property getter, setter or deleter",
            "protectedUsedOutsideOfClass": '"{name}" is protected and used outside of the class in which it is declared',
            "protocolBaseClass": 'Protocol class "{classType}" cannot derive from non-protocol class "{baseType}"',
            "protocolBaseClassWithTypeArgs": "Type arguments are not allowed with Protocol class when using type parameter syntax",
            "protocolIllegal": 'Use of "Protocol" requires Python 3.7 or newer',
            "protocolMemberNotClassVar": 'Protocol class "{className}" does not define "{memberName}" as a ClassVar',
            "protocolNotAllowedInTypeArgument": '"Protocol" cannot be used as a type argument',
            "protocolVarianceContravariant": 'Type variable "{variable}" used in generic protocol "{class}" should be contravariant',
            "protocolVarianceCovariant": 'Type variable "{variable}" used in generic protocol "{class}" should be covariant',
            "protocolVarianceInvariant": 'Type variable "{variable}" used in generic protocol "{class}" should be invariant',
            "protocolUsedInCall": 'Protocol class cannot be used in "{name}" call',
            "relativeImportNotAllowed": 'Relative imports cannot be used with "import .a" form; use "from . import a" instead',
            "recursiveDefinition": 'Type of "{name}" could not be determined because it refers to itself',
            "requiredArgCount": 'Expected a single type argument after "Required"',
            "requiredNotInTypedDict": '"Required" is not allowed in this context',
            "returnInAsyncGenerator": "Return statement with value is not allowed in async generator",
            "returnOutsideFunction": '"return" can be used only within a function',
            "returnMissing": 'Function with declared type of "{returnType}" must return value',
            "returnTypeContravariant": "Contravariant type variable cannot be used in return type",
            "returnTypeMismatch": 'Expression of type "{exprType}" cannot be assigned to return type "{returnType}"',
            "returnTypeUnknown": "Return type is unknown",
            "returnTypePartiallyUnknown": 'Return type, "{returnType}", is partially unknown',
            "revealLocalsArgs": 'Expected no arguments for "reveal_locals" call',
            "revealLocalsNone": "No locals in this scope",
            "revealTypeArgs": 'Expected a single positional argument for "reveal_type" call',
            "revealTypeExpectedTextArg": 'The "expected_text" argument for function "reveal_type" must be a str literal value',
            "revealTypeExpectedTextMismatch": 'Type text mismatch; expected "{expected}" but received "{received}"',
            "revealTypeExpectedTypeMismatch": 'Type mismatch; expected "{expected}" but received "{received}"',
            "selfTypeContext": '"Self" is not valid in this context',
            "selfTypeWithTypedSelfOrCls": '"Self" cannot be used in a function with a `self` or `cls` parameter that has a type annotation other than "Self"',
            "setterGetterTypeMismatch": "Property setter value type is not assignable to the getter return type",
            "singleOverload": '"{name}" is marked as overload, but additional overloads are missing',
            "slotsAttributeError": '"{name}" is not specified in __slots__',
            "slotsClassVarConflict": '"{name}" conflicts with instance variable declared in __slots__',
            "starPatternInAsPattern": 'Star pattern cannot be used with "as" target',
            "starPatternInOrPattern": "Star pattern cannot be ORed within other patterns",
            "starStarWildcardNotAllowed": '** cannot be used with wildcard "_"',
            "staticClsSelfParam": 'Static methods should not take a "self" or "cls" parameter',
            "stdlibModuleOverridden": '"{path}" is overriding the stdlib module "{name}"',
            "strictTypeGuardReturnType": 'Return type of StrictTypeGuard ("{returnType}") is not assignable to value parameter type ("{type}")',
            "stringNonAsciiBytes": "Non-ASCII character not allowed in bytes string literal",
            "stringNotSubscriptable": "String expression cannot be subscripted in type annotation; enclose entire annotation in quotes",
            "stringUnsupportedEscape": "Unsupported escape sequence in string literal",
            "stringUnterminated": "String literal is unterminated",
            "stubFileMissing": 'Stub file not found for "{importName}"',
            "stubUsesGetAttr": 'Type stub file is incomplete; "__getattr__" obscures type errors for module',
            "sublistParamsIncompatible": "Sublist parameters are not supported in Python 3.x",
            "superCallArgCount": 'Expected no more than two arguments to "super" call',
            "superCallFirstArg": 'Expected class type as first argument to "super" call but received "{type}"',
            "superCallSecondArg": 'Second argument to "super" call must be object or class that derives from "{type}"',
            "superCallZeroArgForm": 'Zero-argument form of "super" call is valid only within a class',
            "symbolIsUnbound": '"{name}" is unbound',
            "symbolIsUndefined": '"{name}" is not defined',
            "symbolIsPossiblyUnbound": '"{name}" is possibly unbound',
            "symbolOverridden": '"{name}" overrides symbol of same name in class "{className}"',
            "totalOrderingMissingMethod": 'Class must define one of "__lt__", "__le__", "__gt__", or "__ge__" to use total_ordering',
            "trailingCommaInFromImport": "Trailing comma not allowed without surrounding parentheses",
            "tryWithoutExcept": "Try statement must have at least one except or finally clause",
            "tupleAssignmentMismatch": 'Expression with type "{type}" cannot be assigned to target tuple',
            "tupleInAnnotation": "Tuple expression not allowed in type annotation",
            "tupleIndexOutOfRange": "Index {index} is out of range for type {type}",
            "typeAliasIllegalExpressionForm": "Invalid expression form for type alias definition",
            "typeAliasIsRecursiveDirect": 'Type alias "{name}" cannot use itself in its definition',
            "typeAliasIsRecursiveIndirect": 'Type alias "{name}" cannot refer to itself indirectly in its definition',
            "typeAliasNotInModuleOrClass": "A TypeAlias can be defined only within a module or class scope",
            "typeAliasRedeclared": '"{name}" is declared as a TypeAlias and can be assigned only once',
            "typeAliasStatementIllegal": "Type alias statement requires Python 3.12 or newer",
            "typeArgListExpected": "Expected ParamSpec, ellipsis, or list of types",
            "typeAnnotationCall": "Illegal type annotation: call expression not allowed",
            "typeAnnotationVariable": "Illegal type annotation: variable not allowed unless it is a type alias",
            "typeArgListNotAllowed": "List expression not allowed for this type argument",
            "typeArgsExpectingNone": 'Expected no type arguments for class "{name}"',
            "typeArgsMismatchOne": "Expected one type argument but received {received}",
            "typeArgsMissingForAlias": 'Expected type arguments for generic type alias "{name}"',
            "typeArgsMissingForClass": 'Expected type arguments for generic class "{name}"',
            "typeArgsTooFew": 'Too few type arguments provided for "{name}"; expected {expected} but received {received}',
            "typeArgsTooMany": 'Too many type arguments provided for "{name}"; expected {expected} but received {received}',
            "typeAssignmentMismatch": 'Expression of type "{sourceType}" cannot be assigned to declared type "{destType}"',
            "typeCallNotAllowed": "type() call should not be used in type annotation",
            "typeCommentDeprecated": "Use of type comments is deprecated; use type annotation instead",
            "typedDictAccess": "Could not access item in TypedDict",
            "typedDictBadVar": "TypedDict classes can contain only type annotations",
            "typedDictBaseClass": "All base classes for TypedDict classes must also be TypedDict classes",
            "typedDictDelete": "Could not delete item in TypedDict",
            "typedDictEmptyName": "Names within a TypedDict cannot be empty",
            "typedDictEntryName": "Expected string literal for dictionary entry name",
            "typedDictEntryUnique": "Names within a dictionary must be unique",
            "typedDictExtraArgs": "Extra TypedDict arguments not supported",
            "typedDictFieldRedefinition": 'Type of TypedDict field "{name}" cannot be redefined',
            "typedDictFirstArg": "Expected TypedDict class name as first argument",
            "typedDictSecondArgDict": "Expected dict or keyword parameter as second parameter",
            "typedDictSecondArgDictEntry": "Expected simple dictionary entry",
            "typedDictSet": "Could not assign item in TypedDict",
            "typedDictTotalParam": 'Expected "total" parameter to have a value of True or False',
            "typeExpectedClass": 'Expected type expression but received "{type}"',
            "typeGuardArgCount": 'Expected a single type argument after "TypeGuard"',
            "typeNotAwaitable": '"{type}" is not awaitable',
            "typeNotCallable": '"{expression}" has type "{type}" and is not callable',
            "typeNotIntantiable": '"{type}" cannot be instantiated',
            "typeNotIterable": '"{type}" is not iterable',
            "typeNotSpecializable": 'Could not specialize type "{type}"',
            "typeNotSubscriptable": 'Object of type "{type}" is not subscriptable',
            "typeNotUsableWith": 'Object of type "{type}" cannot be used with "with" because it does not implement {method}',
            "typeNotSupportBinaryOperator": 'Operator "{operator}" not supported for types "{leftType}" and "{rightType}"',
            "typeNotSupportBinaryOperatorBidirectional": 'Operator "{operator}" not supported for types "{leftType}" and "{rightType}" when expected type is "{expectedType}"',
            "typeNotSupportUnaryOperator": 'Operator "{operator}" not supported for type "{type}"',
            "typeNotSupportUnaryOperatorBidirectional": 'Operator "{operator}" not supported for type "{type}" when expected type is "{expectedType}"',
            "typeParameterBoundNotAllowed": "Bound or constraint cannot be used with a variadic type parameter or ParamSpec",
            "typeParameterConstraintTuple": "Type parameter constraint must be a tuple of two or more types",
            "typeParameterExistingTypeParameter": 'Type parameter "{name}" is already in use',
            "typeParametersMissing": "At least one type parameter must be specified",
            "typeParameterNotDeclared": 'Type parameter "{name}" is not included in the type parameter list for "{container}"',
            "typePartiallyUnknown": 'Type of "{name}" is partially unknown',
            "typeUnknown": 'Type of "{name}" is unknown',
            "typeVarAssignedName": 'TypeVar must be assigned to a variable named "{name}"',
            "typeVarAssignmentMismatch": 'Type "{type}" cannot be assigned to type variable "{name}"',
            "typeVarBoundAndConstrained": "TypeVar cannot be both bound and constrained",
            "typeVarBoundGeneric": "TypeVar bound type cannot be generic",
            "typeVarConstraintGeneric": "TypeVar constraint type cannot be generic",
            "typeVarDefaultBoundMismatch": "TypeVar default type must be a subtype of the bound type",
            "typeVarDefaultConstraintMismatch": "TypeVar default type must be one of the constrained types",
            "typeVarFirstArg": "Expected name of TypeVar as first argument",
            "typeVarDefaultInvalidTypeVar": 'Type parameter "{name}" has a default type that refers to one or more type variables that are out of scope',
            "typeVarNoMember": 'TypeVar "{type}" has no member "{name}"',
            "typeVarNotSubscriptable": 'TypeVar "{type}" is not subscriptable',
            "typeVarNotUsedByOuterScope": 'Type variable "{name}" has no meaning in this context',
            "typeVarPossiblyUnsolvable": 'Type variable "{name}" may go unsolved if caller supplies no argument for parameter "{param}"',
            "typeVarScopedToReturnType": 'Type variable "{name}" is scoped to a callable within the return type and cannot be referenced in the function body',
            "typeVarSingleConstraint": "TypeVar must have at least two constrained types",
            "typeVarsNotInGenericOrProtocol": "Generic[] or Protocol[] must include all type variables",
            "typeVarTupleContext": "TypeVarTuple not allowed in this context",
            "typeVarTupleDefaultNotUnpacked": "TypeVarTuple default type must be an unpacked tuple or TypeVarTuple",
            "typeVarTupleMustBeUnpacked": "Unpack operator is required for TypeVarTuple value",
            "typeVarTupleUnknownParam": '"{name}" is unknown parameter to TypeVarTuple',
            "typeVarUnknownParam": '"{name}" is unknown parameter to TypeVar',
            "typeVarUsedByOuterScope": 'TypeVar "{name}" is already in use by an outer scope',
            "typeVarUsedOnlyOnce": 'TypeVar "{name}" appears only once in generic function signature',
            "typeVarVariance": "TypeVar cannot be both covariant and contravariant",
            "typeVarWithoutDefault": '"{name}" cannot appear after "{other}" in type parameter list because it has no default type',
            "unaccessedClass": 'Class "{name}" is not accessed',
            "unaccessedFunction": 'Function "{name}" is not accessed',
            "unaccessedImport": 'Import "{name}" is not accessed',
            "unaccessedSymbol": '"{name}" is not accessed',
            "unaccessedVariable": 'Variable "{name}" is not accessed',
            "unannotatedFunctionSkipped": 'Analysis of function "{name}" is skipped because it unannotated',
            "unexpectedAsyncToken": 'Expected "def", "with" or "for" to follow "async"',
            "unexpectedExprToken": "Unexpected token at end of expression",
            "unexpectedIndent": "Unexpected indentation",
            "unexpectedUnindent": "Unindent not expected",
            "unhashableDictKey": "Dictionary key must be hashable",
            "unhashableSetEntry": "Set entry must be hashable",
            "unionForwardReferenceNotAllowed": "Union syntax cannot be used with string operand; use quotes around entire expression",
            "unionSyntaxIllegal": "Alternative syntax for unions requires Python 3.10 or newer",
            "unionTypeArgCount": "Union requires two or more type arguments",
            "uninitializedInstanceVariable": 'Instance variable "{name}" is not initialized in the class body or __init__ method',
            "unmatchedEndregionComment": "#endregion is missing corresponding #region",
            "unmatchedRegionComment": "#region is missing corresponding #endregion",
            "unnecessaryCast": 'Unnecessary "cast" call; type is already "{type}"',
            "unnecessaryIsInstanceAlways": 'Unnecessary isinstance call; "{testType}" is always an instance of "{classType}"',
            "unnecessaryIsSubclassAlways": 'Unnecessary issubclass call; "{testType}" is always a subclass of "{classType}"',
            "unnecessaryPyrightIgnore": 'Unnecessary "# pyright: ignore" comment',
            "unnecessaryPyrightIgnoreRule": 'Unnecessary "# pyright: ignore" rule: "{name}"',
            "unnecessaryTypeIgnore": 'Unnecessary "# type: ignore" comment',
            "unpackArgCount": 'Expected a single type argument after "Unpack"',
            "unpackedArgInTypeArgument": "Unpacked arguments cannot be used in type argument lists",
            "unpackedArgWithVariadicParam": "Unpacked argument cannot be used for TupleTypeVar parameter",
            "unpackedDictArgumentNotMapping": 'Argument expression after ** must be a mapping with a "str" key type',
            "unpackedSubscriptIllegal": "Unpack operator in subscript requires Python 3.11 or newer",
            "unpackedTypedDictArgument": "Unable to match unpacked TypedDict argument to parameters",
            "unpackedTypeVarTupleExpected": "Expected unpacked TypeVarTuple; use Unpack[{name1}] or *{name2}",
            "unpackExpectedTypedDict": "Expected TypedDict type argument for Unpack",
            "unpackExpectedTypeVarTuple": "Expected TypeVarTuple or Tuple as type argument for Unpack",
            "unpackIllegalInComprehension": "Unpack operation not allowed in comprehension",
            "unpackInAnnotation": "Unpack operator not allowed in type annotation",
            "unpackInDict": "Unpack operation not allowed in dictionaries",
            "unpackInSet": "Unpack operator not allowed within a set",
            "unpackNotAllowed": "Unpack not allowed in this context",
            "unpackOperatorNotAllowed": "Unpack operation not allowed in this context",
            "unpackTuplesIllegal": "Unpack operation not allowed in tuples prior to Python 3.8",
            "unreachableCode": "Code is unreachable",
            "unreachableExcept": "Except clause is unreachable because exception is already handled",
            "unsupportedDunderAllOperation": 'Operation on "__all__" is not supported, so exported symbol list may be incorrect',
            "unusedCallResult": 'Result of call expression is of type "{type}" and is not used; assign to variable "_" if this is intentional',
            "unusedCoroutine": 'Result of async function call is not used; use "await" or assign result to variable',
            "unusedExpression": "Expression value is unused",
            "varAnnotationIllegal": "Type annotations for variables requires Python 3.6 or newer; use type comment for compatibility with previous versions",
            "variableFinalOverride": 'Variable "{name}" is marked Final and overrides non-Final variable of same name in class "{className}"',
            "variadicTypeArgsTooMany": "Type argument list can have at most one unpacked TypeVarTuple or Tuple",
            "variadicTypeParamTooManyAlias": "Type alias can have at most one TypeVarTuple type parameter but received multiple ({names})",
            "variadicTypeParamTooManyClass": "Generic class can have at most one TypeVarTuple type parameter but received multiple ({names})",
            "walrusIllegal": 'Operator ":=" requires Python 3.8 or newer',
            "walrusNotAllowed": 'Operator ":=" not allowed in this context without surrounding parentheses',
            "wildcardInFunction": "Wildcard import not allowed within a class or function",
            "wildcardLibraryImport": "Wildcard import from a library not allowed",
            "yieldFromIllegal": 'Use of "yield from" requires Python 3.3 or newer',
            "yieldFromOutsideAsync": '"yield from" not allowed in an async function',
            "yieldOutsideFunction": '"yield" not allowed outside of a function or lambda',
            "yieldTypeMismatch": 'Expression of type "{exprType}" cannot be assigned to yield type "{yieldType}"',
            "yieldWithinListCompr": '"yield" not allowed inside a list comprehension',
            "zeroCaseStatementsFound": "Match statement must include at least one case statement",
            "zeroLengthTupleNotAllowed": "Zero-length tuple not allowed in this context",
        },
        "DiagnosticAddendum": {
            "argParam": 'Argument corresponds to parameter "{paramName}"',
            "argParamFunction": 'Argument corresponds to parameter "{paramName}" in function "{functionName}"',
            "argsParamMissing": 'Parameter "*{paramName}" has no corresponding parameter',
            "argsPositionOnly": "Position-only parameter mismatch; expected {expected} but received {received}",
            "argumentType": 'Argument type is "{type}"',
            "argumentTypes": "Argument types: ({types})",
            "assignToNone": 'Type cannot be assigned to type "None"',
            "asyncHelp": 'Did you mean "async with"?',
            "baseClassOverriddenType": 'Base class "{baseClass}" provides type "{type}", which is overridden',
            "baseClassOverridesType": 'Base class "{baseClass}" overrides with type "{type}"',
            "dataClassFieldLocation": "Field declaration",
            "dataClassFrozen": '"{name}" is frozen',
            "finalMethod": "Final method",
            "keyNotRequired": '"{name}" is not a required key in "{type}", so access may result in runtime exception',
            "keyRequiredDeleted": '"{name}" is a required key and cannot be deleted',
            "keyUndefined": '"{name}" is not a defined key in "{type}"',
            "functionParamDefaultMissing": 'Parameter "{name}" is missing default argument',
            "functionParamName": 'Parameter name mismatch: "{destName}" versus "{srcName}"',
            "functionReturnTypeMismatch": 'Function return type "{sourceType}" is incompatible with type "{destType}"',
            "functionTooFewParams": "Function accepts too few positional parameters; expected {expected} but received {received}",
            "functionTooManyParams": "Function accepts too many positional parameters; expected {expected} but received {received}",
            "incompatibleGetter": "Property getter method is incompatible",
            "incompatibleSetter": "Property setter method is incompatible",
            "initMethodLocation": 'The __init__ method is defined in class "{type}"',
            "incompatibleDeleter": "Property deleter method is incompatible",
            "initMethodSignature": 'Signature of __init__ is "{type}"',
            "kwargsParamMissing": 'Parameter "**{paramName}" has no corresponding parameter',
            "listAssignmentMismatch": 'Type "{type}" is incompatible with target list',
            "literalAssignmentMismatch": '"{sourceType}" cannot be assigned to type "{destType}"',
            "matchIsNotExhaustiveType": 'Unhandled type: "{type}"',
            "matchIsNotExhaustiveHint": 'If exhaustive handling is not intended, add "case _: pass"',
            "memberSetClassVar": 'Member "{name}" cannot be assigned through a class instance because it is a ClassVar',
            "memberAssignment": 'Expression of type "{type}" cannot be assigned to member "{name}" of class "{classType}"',
            "memberIsAbstract": '"{type}.{name}" is abstract',
            "memberIsAbstractMore": "and {count} more...",
            "memberIsFinalInProtocol": '"{name}" is marked Final in protocol',
            "memberIsInitVar": 'Member "{name}" is an init-only field',
            "memberIsInvariant": '"{name}" is invariant because it is mutable',
            "memberIsNotFinalInProtocol": '"{name}" is not marked Final in protocol',
            "memberTypeMismatch": '"{name}" is an incompatible type',
            "memberUnknown": 'Member "{name}" is unknown',
            "missingProtocolMember": 'Member "{name}" is declared in protocol class "{classType}"',
            "missingGetter": "Property getter method is missing",
            "missingSetter": "Property setter method is missing",
            "missingDeleter": "Property deleter method is missing",
            "namedParamMissingInDest": 'Keyword parameter "{name}" is missing in destination',
            "namedParamMissingInSource": 'Keyword parameter "{name}" is missing in source',
            "namedParamTypeMismatch": 'Keyword parameter "{name}" of type "{sourceType}" cannot be assigned to type "{destType}"',
            "newMethodLocation": 'The __new__ method is defined in class "{type}"',
            "newMethodSignature": 'Signature of __new__ is "{type}"',
            "noOverloadAssignable": 'No overloaded function matches type "{type}"',
            "orPatternMissingName": "Missing names: {name}",
            "overloadSignature": "Overload signature is defined here",
            "overloadNotAssignable": 'One or more overloads of "{name}" is not assignable',
            "overloadWithImplementation": 'The body of a function overload should be "..."',
            "overriddenMethod": "Overridden method",
            "overriddenSymbol": "Overridden symbol",
            "overrideNoOverloadMatches": "No overload signature in override is compatible with base method",
            "overrideNotClassMethod": "Base method is declared as a classmethod but override is not",
            "overrideNotInstanceMethod": "Base method is declared as an instance method but override is not",
            "overrideNotStaticMethod": "Base method is declared as a staticmethod but override is not",
            "overrideParamKeywordNoDefault": 'Keyword parameter "{name}" mismatch: base parameter has default argument value, override parameter does not',
            "overrideParamKeywordType": 'Keyword parameter "{name}" type mismatch: base parameter is type "{baseType}", override parameter is type "{overrideType}"',
            "overrideParamName": 'Parameter {index} name mismatch: base parameter is named "{baseName}", override parameter is named "{overrideName}"',
            "overrideParamNameExtra": 'Parameter "{name}" is missing in base',
            "overrideParamNameMissing": 'Parameter "{name}" is missing in override',
            "overrideParamNamePositionOnly": 'Parameter {index} name mismatch: base parameter is named "{baseName}", override parameter is position-only"',
            "overrideParamNoDefault": "Parameter {index} mismatch: base parameter has default argument value, override parameter does not",
            "overrideParamType": 'Parameter {index} type mismatch: base parameter is type "{baseType}", override parameter is type "{overrideType}"',
            "overridePositionalParamCount": "Positional parameter count mismatch; base method has {baseCount}, but override has {overrideCount}",
            "overrideReturnType": 'Return type mismatch: base method returns type "{baseType}", override returns type "{overrideType}"',
            "overrideType": 'Base class defines type as "{type}"',
            "paramAssignment": 'Parameter {index}: type "{sourceType}" cannot be assigned to type "{destType}"',
            "paramSpecOverload": "ParamSpec cannot be used with overloaded function",
            "paramType": 'Parameter type is "{paramType}"',
            "privateImportFromPyTypedSource": 'Import from "{module}" instead',
            "propertyAccessFromProtocolClass": "A property defined within a protocol class cannot be accessed as a class variable",
            "propertyMethodIncompatible": 'Property method "{name}" is incompatible',
            "propertyMethodMissing": 'Property method "{name}" is missing in override',
            "propertyMissingDeleter": 'Property "{name}" has no defined deleter',
            "propertyMissingSetter": 'Property "{name}" has no defined setter',
            "protocolIncompatible": '"{sourceType}" is incompatible with protocol "{destType}"',
            "protocolMemberClassVar": '"{name}" is not a class variable',
            "protocolMemberMissing": '"{name}" is not present',
            "protocolSourceIsNotConcrete": '"{sourceType}" is not a concrete class type and cannot be assigned to type "{destType}"',
            "readOnlyAttribute": 'Attribute "{name}" is read-only',
            "seeDeclaration": "See declaration",
            "seeClassDeclaration": "See class declaration",
            "seeFunctionDeclaration": "See function declaration",
            "seeMethodDeclaration": "See method declaration",
            "seeParameterDeclaration": "See parameter declaration",
            "seeTypeAliasDeclaration": "See type alias declaration",
            "seeVariableDeclaration": "See variable declaration",
            "tupleEntryTypeMismatch": "Tuple entry {entry} is incorrect type",
            "tupleAssignmentMismatch": 'Type "{type}" is incompatible with target tuple',
            "tupleSizeMismatch": "Element size mismatch; expected {expected} but received {received}",
            "tupleSizeMismatchIndeterminate": "Tuple size mismatch; expected {expected} but received indeterminate number",
            "typeAssignmentMismatch": 'Type "{sourceType}" cannot be assigned to type "{destType}"',
            "typeBound": 'Type "{sourceType}" is incompatible with bound type "{destType}" for type variable "{name}"',
            "typeConstrainedTypeVar": 'Type "{type}" is incompatible with constrained type variable "{name}"',
            "typedDictFieldMissing": '"{name}" is missing from "{type}"',
            "typedDictFieldNotRequired": '"{name}" is not required in "{type}"',
            "typedDictFieldRequired": '"{name}" is required in "{type}"',
            "typedDictFieldTypeMismatch": 'Type "{type}" is not assignable to field "{name}"',
            "typedDictFieldRedefinition": 'Type in parent class is "{parentType}" and type in child class is "{childType}"',
            "typedDictFieldUndefined": '"{name}" is an undefined field in type "{type}"',
            "typedDictFinalMismatch": '"{sourceType}" is incompatible with "{destType}" because of a @final mismatch',
            "typeIncompatible": '"{sourceType}" is incompatible with "{destType}"',
            "typeNotCallable": 'Type "{type}" is not callable',
            "typeNotClass": '"{type}" is not a class',
            "typeParamSpec": 'Type "{type}" is incompatible with ParamSpec "{name}"',
            "typeNotStringLiteral": '"{type}" is not a string literal',
            "typeOfSymbol": 'Type of "{name}" is "{type}"',
            "typeUnsupported": 'Type "{type}" is unsupported',
            "typeVarDefaultOutOfScope": 'Type variable "{name}" is not in scope',
            "typeVarIsContravariant": 'TypeVar "{name}" is contravariant',
            "typeVarIsCovariant": 'TypeVar "{name}" is covariant',
            "typeVarIsInvariant": 'TypeVar "{name}" is invariant',
            "typeVarNotAllowed": "TypeVar or generic type with type arguments not allowed",
            "typeVarUnsolvableRemedy": "Provide an overload that specifies the return type when the argument is not supplied",
            "typeVarsMissing": "Missing type variables: {names}",
            "typeVarTupleRequiresKnownLength": "TypeVarTuple cannot be bound to a tuple of unknown length",
            "unhashableType": 'Type "{type}" is not hashable',
            "unreachableExcept": '"{exceptionType}" is a subclass of "{parentType}"',
            "useDictInstead": "Use Dict[T1, T2] to indicate a dictionary type",
            "useListInstead": "Use List[T] to indicate a list type or Union[T1, T2] to indicate a union type",
            "useTupleInstead": "Use Tuple[T1, ..., Tn] to indicate a tuple type or Union[T1, T2] to indicate a union type",
            "useTypeInstead": "Use Type[T] instead",
            "varianceMismatch": 'Variance of TypeVar "{typeVarName}" is incompatible with base class "{className}"',
        },
        "CodeAction": {
            "addOptionalToAnnotation": 'Add "Optional" to Type Annotation',
            "createTypeStub": "Create Type Stub",
            "createTypeStubFor": 'Create Type Stub For "{moduleName}"',
            "executingCommand": "Executing command",
            "filesToAnalyzeOne": "1 file to analyze",
            "filesToAnalyzeCount": "{count} files to analyze",
            "findingReferences": "Finding references",
            "organizeImports": "Organize Imports",
            "renameShadowedFile": 'Rename "{oldFile}" to "{newFile}"',
        },
        "Refactoring": {
            "moveFile": 'Do you want to update all import references for "{oldModuleName}" to "{newModuleName}"?',
            "moveFileLabel": 'Update all import references for "{oldModuleName}" to "{newModuleName}"?',
            "moveFileDescription": 'Update all import references for "{oldModuleName}" to "{newModuleName}"?',
        },
    }

    parsed_messages: Dict[str, Dict[str, parse.Parser]] = {}
    for category, messages in raw_messages.items():
        cat = parsed_messages[category] = {}
        for name, message in messages.items():
            cat[name] = parse.compile(message, case_sensitive=True)

    return parsed_messages


def snake_case_to_camel_case(name: str) -> str:
    """Converts a snake_case string to a camelCase string."""
    parts = name.split("_")
    return parts[0] + "".join(p.title() for p in parts[1:])


def camel_case_to_snake_case(name: str) -> str:
    """Converts a camelCase string to a snake_case string."""
    return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()


def split_camel_case_words(name: str) -> List[str]:
    """Splits a camelCase string into words."""
    return re.findall(r".[^A-Z]*", name)


def camel_case_to_capitalized_text(name: str) -> str:
    """Converts a camelCase string to a capitalized text string.

    Args:
        name: The camelCase string to convert.

    Returns:
        The capitalized text string.

    Examples:
        >>> camel_case_to_capitalized_text("camelCase")
        'Camel case'

        >>> camel_case_to_capitalized_text("camelCaseString")
        'Camel case string'
    """
    return " ".join(split_camel_case_words(name)).capitalize()


class ParsedDiagnosticAddendum(NamedTuple):
    """A parsed diagnostic addendum."""

    category: str
    result: parse.Result

    @property
    def values(self) -> Dict[str, str]:
        return self.result.named

    @property
    def category_text(self) -> str:
        return camel_case_to_capitalized_text(self.category)


class ParsedDiagnostic(NamedTuple):
    category: str
    result: parse.Result
    addendums: List[ParsedDiagnosticAddendum]

    @property
    def category_text(self) -> str:
        return camel_case_to_capitalized_text(self.category)

    @property
    def values(self) -> Dict[str, str]:
        return self.result.named

    def __rich_repr__(self) -> str:
        cat_str = camel_case_to_capitalized_text(self.category)
        results = [
            f"{camel_case_to_capitalized_text(k)}: {v}" for k, v in self.result.named.items()
        ]
        results_str = textwrap.indent("\n".join(results), "  ")
        return f"{cat_str}:\n{results_str}"


def parse_message(message: str) -> ParsedDiagnostic:
    diagnostic, *addendums = map(str.strip, message.splitlines())
    parsed_addendums = []
    for addendum in addendums:
        for category, parser in parsed_messages["DiagnosticAddendum"].items():
            if parsed := parser.parse(addendum):
                parsed_addendums.append(ParsedDiagnosticAddendum(category, parsed))
                break

    parsed_diagnostics = [
        ParsedDiagnostic(cat, parsed, parsed_addendums)
        for cat, p in parsed_messages["Diagnostic"].items()
        if (parsed := p.parse(diagnostic))
    ]
    if len(parsed_diagnostics) == 0:
        con.log(f"Could not parse diagnostic: {diagnostic}", log_locals=True)
        return ParsedDiagnostic("unknown", parse.parse("result: {mask}", "result: idk"), [])  # todo
    elif len(parsed_diagnostics) > 1:
        con.log(f"Could not parse diagnostic: {diagnostic}", log_locals=True)

    return parsed_diagnostics[0]


parsed_messages = _get_message_parsers()


__all__ = (
    "camel_case_to_capitalized_text",
    "camel_case_to_snake_case",
    "parse_message",
    "parsed_messages",
    "ParsedDiagnostic",
    "ParsedDiagnosticAddendum",
    "snake_case_to_camel_case",
    "split_camel_case_words",
)
