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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
"""Command-line interface. Every Makefile target maps to a subcommand here."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Annotated

import typer
from rich.console import Console
from rich.table import Table

from lockin.config import Config, load_config

app = typer.Typer(
    add_completion=False,
    no_args_is_help=True,
    help="Mortgage Rate Lock-In, Housing Liquidity, and Local Market Dynamics.",
)
console = Console()

ConfigOpt = Annotated[str, typer.Option("--config", "-c", help="Path to a run profile YAML.")]


def _cfg(config: str) -> Config:
    cfg = load_config(config)
    banner = (
        "[bold yellow]SYNTHETIC[/] loan fixtures"
        if cfg.data_class == "SYNTHETIC"
        else "[bold green]REGISTERED[/] loan data"
    )
    console.print(f"profile [bold]{cfg.name}[/] · {banner} · config digest [dim]{cfg.digest()}[/]")
    return cfg


def _report_problems(label: str, problems: list[str]) -> int:
    hard = [p for p in problems if p.startswith("HARD")]
    soft = [p for p in problems if p.startswith("SOFT")]
    info = [p for p in problems if p.startswith("INFO")]
    if not problems:
        console.print(f"  [green]✓[/] {label}: no issues")
        return 0
    for p in hard:
        console.print(f"  [bold red]✗[/] {p}")
    for p in soft:
        console.print(f"  [yellow]![/] {p}")
    for p in info:
        console.print(f"  [dim]i[/] {p}")
    return len(hard)


# ---------------------------------------------------------------------------


@app.command("verify-schema")
def verify_schema() -> None:
    """Check the encoded Freddie Mac layout against its own invariants."""
    from lockin.schemas.freddie import (
        ORIGINATION_FIELDS,
        PERFORMANCE_FIELDS,
        SCHEMA_VERSION,
        VERIFIED_AGAINST,
        ZERO_BALANCE_CODES,
        assert_layout_verified,
    )

    assert_layout_verified()
    console.print(f"[green]✓[/] schema {SCHEMA_VERSION}")
    console.print(
        f"  {len(ORIGINATION_FIELDS)} origination fields, "
        f"{len(PERFORMANCE_FIELDS)} performance fields"
    )
    t = Table("ZB", "official label", "event class", "censored", "priority")
    for z in sorted(ZERO_BALANCE_CODES.values(), key=lambda x: x.priority):
        t.add_row(z.code, z.official_label, z.event_class, str(z.censoring), str(z.priority))
    console.print(t)
    console.print("  verified against:")
    for k, v in VERIFIED_AGAINST.items():
        console.print(f"    {k}: {v}")


@app.command("check-registered-data")
def check_registered_data(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Preflight the registered Freddie Mac archives BEFORE a multi-hour ingest.

    Reads only the head of each member: seconds, not hours. Exits non-zero on a blocker.
    """
    from lockin.preflight import registration_steps, run_preflight

    cfg = _cfg(config)
    pf = run_preflight(cfg)

    for f in pf.findings:
        style = {"BLOCKER": "[bold red]x[/]", "WARNING": "[yellow]![/]", "INFO": "[dim]i[/]"}[
            f.level
        ]
        console.print(f"  {style} {f.message}")

    if pf.files:
        t = Table("kind", "cohort", "fields", "expected", "probed", "source")
        for row in pf.files:
            t.add_row(
                str(row["kind"]),
                str(row["cohort"]),
                str(row.get("modal_field_count", "?")),
                str(row.get("expected_field_count", "?")),
                str(row.get("lines_probed", 0)),
                str(row["source"])[-52:],
            )
        console.print(t)

    # No files at all means the user has not completed registration yet -- which is
    # exactly when they need the steps, so print them BEFORE the blocker summary.
    if not pf.files:
        console.print("\n[bold]Steps only you can perform:[/]")
        for step in registration_steps():
            console.print(f"  {step}")

    if pf.n_blockers:
        console.print(f"\n[bold red]{pf.n_blockers} blocker(s).[/] Do not ingest yet.")
        raise typer.Exit(code=1)

    console.print("\n[green]Preflight clean.[/] Set mortgage.mode and run `make reproduce-sample`.")


@app.command("emit-layout")
def emit_layout() -> None:
    """Regenerate data/reference/freddie_llds_layout.yaml from the schema module.

    The YAML is committed so the field map is reviewable without reading Python; it is
    generated so the two cannot drift. A test enforces that they agree.
    """
    import yaml

    from lockin.config import REPO_ROOT
    from lockin.schemas.freddie import assert_layout_verified, layout_spec

    assert_layout_verified()
    out = REPO_ROOT / "data" / "reference" / "freddie_llds_layout.yaml"
    out.parent.mkdir(parents=True, exist_ok=True)
    with out.open("w") as fh:
        fh.write("# GENERATED by `lockin emit-layout` -- do not hand-edit.\n")
        yaml.safe_dump(layout_spec(), fh, sort_keys=False, allow_unicode=True, width=100)
    console.print(f"[green]OK[/] wrote {out}")


@app.command("fetch-public-data")
def fetch_public_data(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Download the official public series, required and optional."""
    from lockin.adapters import (
        bls_laus,
        census_bps,
        fhfa_hpi,
        hmda,
        omb_cbsa,
        pmms,
        teleworkable,
    )

    cfg = _cfg(config)
    results: dict[str, str] = {}

    for label, fn in (
        ("pmms", lambda: pmms.fetch(cfg)),
        ("fhfa_hpi", lambda: fhfa_hpi.fetch(cfg)),
    ):
        try:
            coverage, rows = fn()
            results[label] = f"ok · {rows:,} rows · {coverage}"
        except Exception as exc:
            results[label] = f"FAILED · {type(exc).__name__}: {exc}"

    if cfg.rates.cross_check_fred:
        try:
            df = pmms.fetch_fred_cross_check(cfg)
            results["fred_mortgage30us"] = f"ok · {df.height:,} rows"
        except Exception as exc:
            results["fred_mortgage30us"] = f"FAILED · {exc}"

    try:
        coverage, rows = census_bps.fetch(cfg)
        results["census_bps"] = f"ok · {rows:,} rows · {coverage}"
    except Exception as exc:
        results["census_bps"] = f"FAILED · {type(exc).__name__}: {exc}"

    try:
        coverage, rows = hmda.fetch(cfg)
        results["hmda"] = f"ok · {rows:,} rows · {coverage}"
    except Exception as exc:
        results["hmda"] = f"FAILED · {type(exc).__name__}: {exc}"

    # Optional sources. Each one closes a specific identification threat, and each is
    # allowed to fail: the pipeline records the absence on every artifact rather than
    # stopping. They are fetched HERE so that a fresh clone actually gets them --
    # previously LAUS was only ever `try_load`ed, so a new checkout ran with the
    # labour-shock threat uncontrolled while the documentation said otherwise.
    optional: dict[str, str] = {}
    try:
        coverage, rows = bls_laus.fetch(cfg)
        optional["bls_laus"] = f"ok · {rows:,} rows · {coverage}"
    except Exception as exc:
        optional["bls_laus"] = f"FAILED · {type(exc).__name__}: {exc}"

    try:
        counts = teleworkable.fetch(cfg)
        optional["teleworkable"] = f"ok · {counts['state']} states · {counts['msa']} CBSAs"
    except Exception as exc:
        optional["teleworkable"] = f"FAILED · {type(exc).__name__}: {exc}"

    # Metropolitan variants, fetched only when the run is actually at MSA geography:
    # each costs real requests against a public service, and the state-level run has no
    # use for them.
    if cfg.panel.geography == "msa":
        for label, fn in (
            ("hmda_msa", lambda: hmda.fetch_msa(cfg)),
            ("census_bps_metro", lambda: census_bps.fetch_metro(cfg)),
            ("bls_laus_metro", lambda: bls_laus.fetch_metro(cfg)),
        ):
            try:
                coverage, rows = fn()
                optional[label] = f"ok · {rows:,} rows · {coverage}"
            except Exception as exc:
                optional[label] = f"FAILED · {type(exc).__name__}: {exc}"

    try:
        cw = omb_cbsa.fetch(cfg)
        optional["omb_cbsa"] = (
            f"ok · {cw['codes']:,} codes · {cw.get('stable', 0):,} stable across "
            f"{len(omb_cbsa.VINTAGES)} vintages"
        )
    except Exception as exc:
        optional["omb_cbsa"] = f"FAILED · {type(exc).__name__}: {exc}"

    t = Table("source", "tier", "result")
    for k, v in results.items():
        t.add_row(k, "required", v)
    for k, v in optional.items():
        t.add_row(k, "optional", v)
    console.print(t)
    if any(v.startswith("FAILED") for v in results.values()):
        console.print("[yellow]Some sources failed. The pipeline continues with what is cached.[/]")
    for k, v in optional.items():
        if v.startswith("FAILED"):
            console.print(
                f"[yellow]{k} unavailable — the threat it addresses stays UNCONTROLLED "
                "and every artifact records that.[/]"
            )


@app.command("prepare-sample-data")
def prepare_sample_data(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Generate labeled SYNTHETIC loan fixtures (no restricted data involved)."""
    from lockin.adapters import freddie_llds, pmms
    from lockin.fixtures import generate
    from lockin.rates import monthly_market_rate

    cfg = _cfg(config)
    console.print(freddie_llds.availability_message(cfg))
    if cfg.mortgage.mode != "synthetic" and freddie_llds.discover(cfg):
        console.print("[green]Registered data present; skipping fixture generation.[/]")
        return

    rates = monthly_market_rate(pmms.load(cfg), series=cfg.rates.series)
    summary = generate(cfg, rates)
    console.print(
        f"[green]✓[/] wrote {len(summary.files)} SYNTHETIC files: "
        f"{summary.n_loans:,} loans, {summary.n_performance_rows:,} loan-months, "
        f"cohorts {summary.cohorts}, seed {summary.seed}"
    )
    console.print("[yellow]These are synthetic. No number derived from them is a finding.[/]")


@app.command("ingest-mortgages")
def ingest_mortgages(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Parse origination and monthly performance files into partitioned Parquet."""
    from lockin.ingest import origination, performance

    cfg = _cfg(config)
    o = origination.ingest(cfg)
    console.print(f"[green]✓[/] origination: {sum(o.values()):,} loans {dict(o)}")
    p = performance.ingest(cfg)
    console.print(f"[green]✓[/] performance: {sum(p.values()):,} loan-months {dict(p)}")


@app.command("build-loan-events")
def build_loan_events_cmd(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Build the documented loan-event table (exits, censoring, left truncation)."""
    from lockin.events import build_loan_events, validate_events, write_loan_events

    cfg = _cfg(config)
    events = build_loan_events(cfg)
    hard = _report_problems("loan events", validate_events(events))
    path, summ = write_loan_events(cfg, events)
    console.print(f"[green]✓[/] {events.height:,} loans -> {path}")
    t = Table("event type", "loans", "share")
    for row in summ["by_event_type"]:
        t.add_row(
            str(row["event_type"]),
            f"{int(row['n_loans']):,}",
            f"{100 * int(row['n_loans']) / events.height:.1f}%",
        )
    console.print(t)
    if hard:
        raise typer.Exit(code=1)


@app.command("build-lockin")
def build_lockin_cmd(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Attach point-in-time market rates and compute all lock-in measures."""
    from lockin.adapters import fhfa_hpi, pmms
    from lockin.episodes import build_episodes, validate_episodes, write_episodes
    from lockin.events import load_loan_events
    from lockin.rates import assert_no_look_ahead, monthly_market_rate

    cfg = _cfg(config)
    rates = monthly_market_rate(pmms.load(cfg), series=cfg.rates.series)
    assert_no_look_ahead(rates)
    console.print(f"  point-in-time market rates: {rates.height} months, no look-ahead ✓")

    try:
        hpi_q = fhfa_hpi.load_series(
            cfg,
            flavor=cfg.panel.hpi_flavor,
            frequency=cfg.panel.hpi_frequency,
            level="State",
            seasonal=cfg.panel.hpi_seasonal,
        )
        # The episode table needs a monthly index value to scale LTV. A quarterly
        # index expanded by holding the level within the quarter is acceptable for
        # that purpose and is labeled in index_basis; it is NEVER used as an outcome.
        hpi = fhfa_hpi.to_monthly(hpi_q)
        console.print(
            f"  FHFA HPI ({cfg.panel.hpi_flavor}, {cfg.panel.hpi_frequency}, State): "
            f"{hpi_q.height:,} rows -> {hpi.height:,} monthly rows "
            f"(basis: {hpi['index_basis'][0]})"
        )
    except (FileNotFoundError, ValueError) as exc:
        console.print(f"  [yellow]![/] HPI unavailable ({exc}); estimated LTV degrades")
        hpi = None

    events = load_loan_events(cfg)
    # Build and write one cohort at a time. Collecting all cohorts at once
    # materialises the whole episode table, which OOM-kills the process on the full
    # Standard dataset. See lockin.episodes.write_episodes.
    cohorts = sorted(set(events["cohort"].unique().to_list()))
    if len(cohorts) > 1:
        path, n = write_episodes(
            cfg,
            build=lambda c: build_episodes(cfg, events, rates, hpi, cohort=c),
            cohorts=cohorts,
        )
    else:
        path, n = write_episodes(cfg, build_episodes(cfg, events, rates, hpi))
    console.print(f"[green]✓[/] {n:,} loan-month episodes -> {path}")
    hard = _report_problems("episodes", validate_episodes(cfg))
    if hard:
        raise typer.Exit(code=1)


@app.command("build-local-panel")
def build_local_panel_cmd(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Build the geography-month active stock and the local housing-market panel."""
    from lockin.panel.build import build_local_panel
    from lockin.stock import build_active_stock

    cfg = _cfg(config)
    stock, spath = build_active_stock(cfg)
    console.print(
        f"[green]✓[/] active mortgage stock: {stock.height:,} geography-months -> {spath}"
    )
    panel, ppath, notes = build_local_panel(cfg)
    console.print(f"[green]✓[/] local market panel: {panel.height:,} rows -> {ppath}")
    for n in notes:
        console.print(f"  [dim]·[/] {n}")


@app.command("validate-data")
def validate_data(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Schema, coverage, checksum, and internal-consistency validation."""
    from lockin.validate import run_all_validations

    cfg = _cfg(config)
    result = run_all_validations(cfg)
    for section, problems in result["sections"].items():  # type: ignore[index]
        console.print(f"[bold]{section}[/]")
        _report_problems(section, problems)
    console.print(
        f"\n[bold]{result['n_hard']}[/] hard, [bold]{result['n_soft']}[/] soft, "
        f"[bold]{result['n_info']}[/] informational"
    )
    if int(result["n_hard"]) > 0:  # type: ignore[arg-type]
        raise typer.Exit(code=1)


@app.command("estimate-hazards")
def estimate_hazards(config: ConfigOpt = "configs/sample.yaml") -> None:
    """KM/CIF description, discrete-time logit and cloglog, Cox, competing risks."""
    from lockin.survival.run import run_hazard_ladder

    cfg = _cfg(config)
    written = run_hazard_ladder(cfg)
    for name, path in written.items():
        console.print(f"  [green]✓[/] {name} -> {path}")


@app.command("estimate-local-effects")
def estimate_local_effects(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Continuous-treatment event study, DiD panel, pre-trends, placebos."""
    from lockin.panel.eventstudy import run_event_studies

    cfg = _cfg(config)
    written = run_event_studies(cfg)
    for name, path in written.items():
        console.print(f"  [green]✓[/] {name} -> {path}")


@app.command("robustness")
def robustness(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Run the robustness and falsification grid."""
    from lockin.panel.robustness import run_robustness_grid

    cfg = _cfg(config)
    path, n_fail = run_robustness_grid(cfg)
    console.print(f"  [green]✓[/] robustness grid -> {path} ({n_fail} cells flagged)")


@app.command("benchmark")
def benchmark(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Compare against published mortgage lock-in research benchmarks."""
    from lockin.benchmark import run_benchmark

    cfg = _cfg(config)
    path = run_benchmark(cfg)
    console.print(f"  [green]✓[/] benchmark comparison -> {path}")


@app.command("simulate-policy")
def simulate_policy(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Run the model-dependent policy counterfactual scenarios."""
    from lockin.simulate.scenarios import run_scenarios

    cfg = _cfg(config)
    written = run_scenarios(cfg)
    for name, path in written.items():
        console.print(f"  [green]✓[/] {name} -> {path}")
    console.print("[yellow]Scenarios are model-dependent projections, not forecasts.[/]")


@app.command("report")
def report(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Regenerate every report in reports/ from result artifacts."""
    from lockin.reporting.render import render_all

    cfg = _cfg(config)
    written = render_all(cfg)
    for p in written:
        console.print(f"  [green]✓[/] {p}")


@app.command("status")
def status(config: ConfigOpt = "configs/sample.yaml") -> None:
    """Print pipeline state: which stages have run and what they produced."""
    from lockin.pipeline_status import pipeline_status

    cfg = _cfg(config)
    st = pipeline_status(cfg)
    t = Table("stage", "state", "detail")
    for row in st["stages"]:  # type: ignore[index]
        mark = "[green]✓[/]" if row["ok"] else "[red]✗[/]"
        t.add_row(str(row["stage"]), mark, str(row["detail"]))
    console.print(t)
    console.print(json.dumps({k: v for k, v in st.items() if k != "stages"}, indent=2))


@app.command("dump-artifact")
def dump_artifact(group: str, name: str, config: ConfigOpt = "configs/sample.yaml") -> None:
    """Print one result artifact as JSON."""
    from lockin.artifacts import read_artifact

    cfg = load_config(config)
    console.print_json(json.dumps(read_artifact(cfg, group, name)))


def app_main() -> None:  # pragma: no cover - entry point
    app()


if __name__ == "__main__":  # pragma: no cover
    app_main()


def _unused(p: Path) -> None:  # pragma: no cover
    return None