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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""The catalog: which patterns this bundle teaches, and exactly what each one claims.

A card here is not a snippet to paste. Every card names a rule in ``lingologos_python.rules`` that
decides whether the shape is really present in a given function and writes the text for
it, plus the lock test that rule appends to the matching test file. The card is what a
person reads before applying anything; the rule is what runs; ``patterns/`` holds the rows
that prove the card and the rule still say the same thing.

Three limits are written into the cards rather than assumed:

* A card claims one shape. It says what has to be true for the pattern to apply, and the
  reason codes the rule answers with when it is not, so a refusal is a result with a name
  and not a stack trace.
* A card claims a companion, not a wish. The lock test is part of the pattern because a
  rewrite nobody checks is a claim nobody verified, and the lock is written so that it
  fails when the primary edit did not land.
* A card claims a minimum assurance. Applying a pattern is a commit, and the commit needs
  the number of independent provers the card asks for.
"""

from __future__ import annotations

import ast
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Dict, List, Optional, Sequence, Tuple

from lingologos_python import rules
from lingologos_python.ast_graph import discover_python_files

# Target syntax: a workspace-relative path, then the module level function, split by "::".
TARGET_SEPARATOR = "::"

FAMILIES: Tuple[str, ...] = ("contracts", "mutation", "resources", "shape", "typing")


@dataclass(frozen=True)
class PatternSpec:
    """One card: the shape, the rule that recognises it, and what applying it claims."""

    pattern_id: str
    family: str
    intent_tags: Tuple[str, ...]
    rule: str
    shape: str
    rationale: str
    preconditions: Tuple[str, ...]
    companions: Tuple[str, ...]
    lock_claims: str
    refuses_as: Tuple[str, ...]
    min_assurance: int = 3

    def target_of(self, rel_posix: str, symbol: str) -> str:
        return "%s%s%s" % (rel_posix.replace("\\", "/"), TARGET_SEPARATOR, symbol)

    def to_row(self, case_id: str, target: str, edits: Sequence[rules.Edit], expect: str, reason_code: str = "") -> Dict[str, object]:
        """The corpus row for one run of this card against one target."""

        row: Dict[str, object] = {
            "case_id": case_id,
            "language": "python",
            "family": self.family,
            "intent_tags": list(self.intent_tags),
            "edits": [
                {"file": edit.file, "search": edit.search, "replace": edit.replace, "label": edit.label}
                for edit in edits
            ],
            "expect": expect,
            "note": self.shape,
            "pattern_id": self.pattern_id,
            "rule": self.rule,
            "targets": [target],
            "min_assurance": self.min_assurance,
        }
        if reason_code:
            row["reason_code"] = reason_code
        return row


def _card(
    pattern_id: str,
    family: str,
    intent_tags: Sequence[str],
    shape: str,
    rationale: str,
    preconditions: Sequence[str],
    companions: Sequence[str],
    lock_claims: str,
    refuses_as: Sequence[str],
) -> PatternSpec:
    return PatternSpec(
        pattern_id=pattern_id,
        family=family,
        intent_tags=tuple(intent_tags),
        rule=pattern_id,
        shape=shape,
        rationale=rationale,
        preconditions=tuple(preconditions),
        companions=tuple(companions),
        lock_claims=lock_claims,
        refuses_as=tuple(refuses_as),
    )


# Every card writes its companion in the same place: the test file this layout pairs with
# the source file by name. Which function goes there differs per card, and that is what
# the lock claim states.
LOCK_COMPANION = (
    "one test function appended to the test file paired by name, tests/test_<module>.py, "
    "in the same run as the source change"
)

PATTERNS: Dict[str, PatternSpec] = {
    spec.pattern_id: spec
    for spec in (
        _card(
            "annotate-literal-defaults",
            "typing",
            ("annotate", "defaults", "types"),
            "a module level function whose parameter has a literal default and no annotation",
            "the default already states the type, and a caller reading the signature has to guess it. "
            "Writing it down is what lets a type checker see the boundary of the module.",
            (
                "the function is defined at module level, not nested",
                "the parameter is not annotated already",
                "the default is a str, int, float or bool literal, so the type is readable from it",
                "the file is ASCII text with LF endings and spaces for indentation",
            ),
            (LOCK_COMPANION,),
            "the signature of the function carries the annotation the pattern added and the default it started with",
            (rules.ALREADY_ANNOTATED, rules.NOT_A_MODULE_FUNCTION, rules.NOT_ASCII_TARGET, rules.CRLF_TARGET),
        ),
        _card(
            "mutable-default-to-none",
            "mutation",
            ("defaults", "aliasing", "mutation"),
            "a module level function whose parameter defaults to a list, dict or set built at definition time",
            "one default object is created once and handed to every call that omits the argument, so a call "
            "that mutates it changes what the next caller sees. The rewrite makes the absence explicit.",
            (
                "the function is defined at module level, not nested",
                "the default is an empty list, dict or set literal, or a bare list(), dict() or set() call",
                "that parameter carries no annotation, because widening an annotation is a second change",
                "the guard is not already the first line of the body",
                "the file is ASCII text with LF endings and spaces for indentation",
            ),
            (LOCK_COMPANION,),
            "the default is None, the guard is in the source, and two calls that omit the argument answer differently",
            (
                rules.NOT_A_MUTABLE_DEFAULT,
                rules.ANNOTATED_MUTABLE_DEFAULT,
                rules.GUARD_ALREADY_PRESENT,
                rules.NOT_A_MODULE_FUNCTION,
            ),
        ),
        _card(
            "chain-to-registry",
            "shape",
            ("dispatch", "registry", "extension"),
            "a module level function that dispatches an if/elif chain of one name compared to text literals",
            "adding a kind means editing the middle of a chain, and a missing branch silently falls through. "
            "A mapping of kind to handler makes the set of kinds one visible object and the refusal one place.",
            (
                "every branch tests the same parameter against a text literal and returns one call",
                "each branch is a call of a name defined in the same module, taking plain parameters",
                "the last branch raises, so an unknown kind is refused rather than answered with None",
                "the function takes plain positional parameters only",
            ),
            (LOCK_COMPANION,),
            "the source holds the mapping and no elif, each kind still answers as the chain answered, and an "
            "unknown kind is still refused",
            (rules.NO_DISPATCH_CHAIN, rules.BRANCH_SHAPE_MISMATCH, rules.NOT_A_MODULE_FUNCTION),
        ),
        _card(
            "open-to-context-manager",
            "resources",
            ("files", "lifetime", "resources"),
            "a module level function that opens a file into a name and closes that name itself",
            "a close that is not tied to the scope is skipped by the one path that raises on the way out, and "
            "the reader has to trace every exit to believe the handle is closed.",
            (
                "the assignment is open(...) directly, with no wrapper between the call and the name",
                "the name is closed by an expression statement whose target is that name",
                "the name is used only inside that function and never stored or returned",
                "the function does not already open the handle inside a with block",
            ),
            (LOCK_COMPANION,),
            "the source opens inside a with block and never calls close, and a file written in a temporary "
            "directory is read back through the rewritten function",
            (rules.ALREADY_SCOPED, rules.NO_BARE_OPEN, rules.HANDLE_ESCAPE, rules.NOT_A_MODULE_FUNCTION),
        ),
        _card(
            "bare-assert-to-explicit-raise",
            "contracts",
            ("preconditions", "errors", "contracts"),
            "a module level function whose first statement is an assert guarding its arguments",
            "an assert is a development check that a normal run may switch off, so a precondition written with "
            "it is a contract that stops holding when someone passes -O. The rewrite keeps the same exception.",
            (
                "the assert is the first statement of the function, so it is a precondition and not a check in the middle",
                "the message text, when there is one, is kept word for word",
                "the function still raises AssertionError, so a caller that catches it keeps catching it",
            ),
            (LOCK_COMPANION,),
            "the source carries the raise and no assert line, and the call still refuses the argument the check "
            "refused, with the message it carried",
            (rules.NOT_THE_FIRST_STATEMENT, rules.NOT_A_MODULE_FUNCTION, rules.CRLF_TARGET),
        ),
    )
}

PATTERN_IDS: Tuple[str, ...] = tuple(sorted(PATTERNS))


def pattern_card(pattern_id: str) -> PatternSpec:
    spec = PATTERNS.get(pattern_id)
    if spec is None:
        raise KeyError("unknown pattern: '%s'" % pattern_id)
    return spec


def split_target(target: str) -> Tuple[str, str]:
    """Split ``path::function`` into a workspace-relative path and a function name."""

    if TARGET_SEPARATOR not in target:
        raise ValueError("target must be written as 'path/to/file.py::function': '%s'" % target)
    rel_posix, symbol = target.split(TARGET_SEPARATOR, 1)
    rel_posix = rel_posix.replace("\\", "/").strip()
    symbol = symbol.strip()
    if not rel_posix or not symbol:
        raise ValueError("target must name both a file and a function: '%s'" % target)
    return rel_posix, symbol


@dataclass(frozen=True)
class PatternPlan:
    """What applying a card to one target would write, or why it refuses to."""

    pattern_id: str
    target: str
    edits: Tuple[rules.Edit, ...]
    evidence: Tuple[str, ...]
    min_assurance: int
    refused: bool = False
    reason_code: str = ""
    detail: str = ""

    @property
    def files(self) -> Tuple[str, ...]:
        return tuple(edit.file for edit in self.edits)

    def primary(self) -> rules.Edit:
        if not self.edits:
            raise ValueError("a refused plan writes nothing")
        return self.edits[0]

    def companions(self) -> Tuple[rules.Edit, ...]:
        return self.edits[1:]

    def to_row(self, case_id: str) -> Dict[str, object]:
        spec = pattern_card(self.pattern_id)
        expect = "REFUSED" if self.refused else "VERIFIED"
        return spec.to_row(
            case_id,
            self.target,
            () if self.refused else self.edits,
            expect,
            self.reason_code if self.refused else "",
        )

    def summary(self) -> str:
        if self.refused:
            return "%s refuses %s: %s (%s)" % (self.pattern_id, self.target, self.detail, self.reason_code)
        return "%s applies to %s and writes %s" % (self.pattern_id, self.target, ", ".join(self.files))


def _workspace_reader(root: Path) -> Callable[[str], Optional[str]]:
    def read(rel_posix: str) -> Optional[str]:
        path = root / Path(*rel_posix.split("/"))
        if not path.is_file():
            return None
        return path.read_text(encoding="utf-8", newline="")

    return read


def module_level_functions(text: str) -> Tuple[str, ...]:
    """Names defined at module level, the only functions a card in this catalog claims."""

    try:
        tree = ast.parse(text)
    except SyntaxError:
        return ()
    return tuple(node.name for node in tree.body if isinstance(node, ast.FunctionDef))


def scan_pattern(root: str | Path, pattern_id: str, *, files: Optional[Sequence[str]] = None) -> List[Tuple[str, rules.RuleHit]]:
    """Every target under one root a card applies to, as ``path::function`` labels."""

    spec = pattern_card(pattern_id)
    rule = rules.RULES[spec.rule]
    workspace = Path(root).resolve()
    reader = _workspace_reader(workspace)
    found: List[Tuple[str, rules.RuleHit]] = []
    for rel in sorted(files if files is not None else discover_python_files(workspace)):
        text = reader(rel)
        if text is None:
            continue
        for symbol in module_level_functions(text):
            target, miss = rules.open_target(rel, symbol, reader)
            if target is None:
                continue
            outcome = rule(target)
            if isinstance(outcome, rules.RuleHit):
                found.append((rules.target_label(rel, symbol), outcome))
    return found


def plan_pattern(root: str | Path, pattern_id: str, target: Optional[str] = None) -> PatternPlan:
    """Decide what a card would write in a real workspace, or why it refuses.

    Without an explicit target the catalog scans the workspace, and more than one match is
    a refusal: the caller has to choose, because applying a pattern everywhere it happens
    to fit is not what a card claims.
    """

    spec = pattern_card(pattern_id)
    rule = rules.RULES[spec.rule]
    workspace = Path(root).resolve()
    reader = _workspace_reader(workspace)

    if target is None:
        found = scan_pattern(workspace, pattern_id)
        if not found:
            return PatternPlan(
                pattern_id=pattern_id,
                target="",
                edits=(),
                evidence=(),
                min_assurance=spec.min_assurance,
                refused=True,
                reason_code=rules.NO_SUCH_FUNCTION,
                detail="no module level function under '%s' is in the shape this card claims" % workspace,
            )
        if len(found) > 1:
            return PatternPlan(
                pattern_id=pattern_id,
                target="",
                edits=(),
                evidence=(),
                min_assurance=spec.min_assurance,
                refused=True,
                reason_code="AMBIGUOUS_TARGET",
                detail="this card fits %d targets, name one: %s" % (len(found), ", ".join(label for label, _hit in found)),
            )
        target = found[0][0]

    rel_posix, symbol = split_target(target)
    opened, miss = rules.open_target(rel_posix, symbol, reader)
    if opened is None and miss is not None:
        return PatternPlan(
            pattern_id=pattern_id,
            target=rules.target_label(rel_posix, symbol),
            edits=(),
            evidence=(),
            min_assurance=spec.min_assurance,
            refused=True,
            reason_code=miss.reason_code,
            detail=miss.detail,
        )
    assert opened is not None
    outcome = rule(opened)
    if isinstance(outcome, rules.RuleMiss):
        return PatternPlan(
            pattern_id=pattern_id,
            target=outcome.target,
            edits=(),
            evidence=(),
            min_assurance=spec.min_assurance,
            refused=True,
            reason_code=outcome.reason_code,
            detail=outcome.detail,
        )
    return PatternPlan(
        pattern_id=pattern_id,
        target=outcome.target,
        edits=outcome.edits,
        evidence=outcome.evidence,
        min_assurance=spec.min_assurance,
    )


def render_card(spec: PatternSpec) -> str:
    """The card as a person reads it in a terminal."""

    lines = [
        spec.pattern_id,
        "  family   %s" % spec.family,
        "  intent   %s" % ", ".join(spec.intent_tags),
        "  shape    %s" % spec.shape,
        "  why      %s" % spec.rationale,
        "  needs",
    ]
    lines += ["    - %s" % item for item in spec.preconditions]
    lines.append("  companion")
    lines += ["    - %s" % item for item in spec.companions]
    lines.append("  lock     %s" % spec.lock_claims)
    lines.append("  refuses  %s" % ", ".join(spec.refuses_as))
    lines.append("  needs assurance >= %d to commit" % spec.min_assurance)
    return "\n".join(lines)