File size: 7,851 Bytes
7fd88a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
#!/usr/bin/env python3
"""Generate an exact Markdown inventory of routes, commands, skills, and Python callables.

The version label and default output filename follow the package VERSION file
(``FUNCIONES_V20.md`` for 20.x); nothing about the version is hard-coded here.
"""

from __future__ import annotations

import argparse
import ast
import importlib.util
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
from agent_version import AGENT_VERSION, major_label  # noqa: E402

LABEL = major_label()  # e.g. "v16"


def format_signature(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
    """Render a stable source-level function signature from an AST node."""
    arguments = ast.unparse(node.args)
    prefix = "async " if isinstance(node, ast.AsyncFunctionDef) else ""
    returns = f" -> {ast.unparse(node.returns)}" if node.returns else ""
    return f"{prefix}{node.name}({arguments}){returns}"


class CallableVisitor(ast.NodeVisitor):
    """Collect functions and methods with their qualified names."""

    def __init__(self):
        self.scope: list[str] = []
        self.items: list[tuple[str, str, str]] = []

    def visit_ClassDef(self, node: ast.ClassDef) -> None:
        self.scope.append(node.name)
        self.generic_visit(node)
        self.scope.pop()

    def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
        qualified = ".".join(self.scope + [node.name])
        doc = (ast.get_docstring(node) or "").splitlines()
        self.items.append((qualified, format_signature(node), doc[0] if doc else ""))
        self.scope.append(node.name)
        self.generic_visit(node)
        self.scope.pop()

    def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
        self.visit_FunctionDef(node)


def python_inventory(path: Path) -> list[tuple[str, str, str]]:
    """Return every function and method declared in one Python file."""
    tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
    visitor = CallableVisitor()
    visitor.visit(tree)
    return visitor.items


def first_heading(path: Path) -> str:
    """Return the first Markdown heading, falling back to the filename."""
    lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
    start = 0
    if lines and lines[0].strip() == "---":
        for index, line in enumerate(lines[1:], 1):
            if line.strip() == "---":
                start = index + 1
                break
    for line in lines[start:]:
        if line.startswith("# "):
            return line[2:].strip()
    return path.stem


def load_routes() -> dict:
    """Load app.py in place and return its route map."""
    spec = importlib.util.spec_from_file_location("re_infra_app", ROOT / "app.py")
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module.ROUTES


def generate_inventory() -> str:
    """Generate the complete Spanish function inventory as Markdown."""
    routes = load_routes()
    commands = sorted((ROOT / "commands").glob("*.md"))
    skills = sorted((ROOT / "skills").glob("*/SKILL.md"))
    scripts = sorted((ROOT / "scripts").glob("*.py"))
    data_files = sorted((ROOT / "data").glob("*.json"))
    references = sorted((ROOT / "references").rglob("*.md"))

    lines = [
        f"# Funciones exactas — Real Estate & Infrastructure Agent {LABEL} ({AGENT_VERSION})",
        "",
        f"Este inventario se genera desde los archivos reales de {LABEL}. Incluye rutas,",
        "comandos, skills, scripts y todas las funciones/métodos Python declarados.",
        "",
        "## Rutas del agente",
        "",
    ]
    for route, (route_commands, route_skills, route_scripts) in routes.items():
        lines.extend([
            f"### `{route}`",
            "",
            f"- Comandos: {', '.join(f'`{item}`' for item in route_commands)}",
            f"- Skills: {', '.join(f'`{item}`' for item in route_skills)}",
            f"- Scripts: {', '.join(f'`{item}.py`' for item in route_scripts)}",
            "",
        ])

    lines.extend(["## Comandos disponibles", ""])
    for path in commands:
        lines.append(f"- `{path.stem}` — {first_heading(path)} (`commands/{path.name}`)")

    lines.extend(["", "## Skills disponibles", ""])
    lines.append(f"- `real-estate-infra-agent` — skill raíz y router (`SKILL.md`)")
    for path in skills:
        lines.append(f"- `{path.parent.name}` — {first_heading(path)} (`skills/{path.parent.name}/SKILL.md`)")

    lines.extend(["", "## Programa de toma y validación de datos", ""])
    lines.extend([
        "- `update_market_data.py`: descarga una instantánea trazable de Catastro, INE e Idealista; no sustituye una descarga fallida por precios incrustados.",
        "- `catastro_idealista_real.py`: cliente Catastro por coordenadas, referencia o dirección, y cliente Idealista con OAuth.",
        "- `market_intelligence.py`: clasifica suelo, obtiene precios, calcula tendencias/proyecciones y bloquea conclusiones sin datos web vivos.",
        "- `legal_monitor.py`: descarga y clasifica novedades del BOE y boletines autonómicos para el período solicitado.",
        "- `opposition_tierra.py`: comprueba trazabilidad, actualidad, soporte de claims, cálculos y lagunas antes del arbitraje adversarial.",
        "- Validadores deterministas: jurisdicción, DSCR, LTV, impuestos de transmisión, fiscalidad, contratos y pre-visado.",
        "",
        "## Todas las funciones y métodos Python",
        "",
    ])
    total_callables = 0
    for path in [ROOT / "app.py", *scripts, *sorted((ROOT / "tests").glob("*.py"))]:
        relative = path.relative_to(ROOT)
        items = python_inventory(path)
        total_callables += len(items)
        lines.extend([f"### `{relative}`", ""])
        if not items:
            lines.append("- No declara funciones o métodos.")
        for qualified, signature, doc in items:
            description = f" — {doc}" if doc else ""
            lines.append(f"- `{qualified}`: `{signature}`{description}")
        lines.append("")

    lines.extend([
        "## Datos y referencias conservados",
        "",
        f"- Archivos JSON de datos: **{len(data_files)}**",
        f"- Referencias Markdown: **{len(references)}**",
        f"- Comandos: **{len(commands)}**",
        f"- Skills especializados: **{len(skills)}** más el skill raíz",
        f"- Scripts Python: **{len(scripts)}** más `app.py`",
        f"- Funciones y métodos Python declarados: **{total_callables}**",
        "",
        f"Los archivos heredados de v14/v15/v16 permanecen en su ruta original. {LABEL}",
        "lee el IPV del INE de la tabla base 2025 (80270) y detecta tablas STALE por",
        "calendario de publicación; re-verifica las fuentes CCAA del monitor legal",
        "(BOPV RSS, BOJA Atom s51+s54, DOGC datos abiertos; DOGV sin feed) con estado",
        "PARTIAL por fuente; y conserva las correcciones de v16 (identidad de versión,",
        "matriz de jurisdicciones, idioma, series INE, HTTPS Catastro, CLI del monitor).",
    ])
    return "\n".join(lines) + "\n"


def build_parser() -> argparse.ArgumentParser:
    """Build the inventory CLI parser."""
    parser = argparse.ArgumentParser(
        description=f"Generate the {LABEL} function inventory")
    parser.add_argument("--output", type=Path,
                        default=ROOT / f"FUNCIONES_{LABEL.upper()}.md")
    return parser


def main() -> int:
    """Write the generated inventory to the requested path."""
    args = build_parser().parse_args()
    args.output.write_text(generate_inventory(), encoding="utf-8")
    print(args.output)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())