File size: 5,169 Bytes
2379054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
agent/code_tools.py
Tools for the Code Agent – wraps core functions + SQLite + VBA generation.
"""

import os

from core.engineering import run_compliance_checks, calculate_lift, calculate_slue
from core.xml_parser import parse_station_base
from core.survey_processor import SurveyImporter
from core.excel_export import write_workbook
from core.database import query_chainages, query_survey_features


def get_tool(name):
    return TOOLS.get(name)


def generate_vba_from_template(template_name: str, placeholders: dict) -> str:
    """
    Read a VBA template from templates/vba/{template_name}.bas.template,
    replace {{PLACEHOLDER}} with values from placeholders dict,
    and return the filled script.
    """
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    template_path = os.path.join(root, "templates", "vba", f"{template_name}.bas.template")
    if not os.path.exists(template_path):
        return f"Template {template_name} not found."
    try:
        with open(template_path, "r", encoding="utf-8") as f:
            content = f.read()
    except OSError as exc:
        return f"Could not read template {template_name}: {exc}"
    for key, value in placeholders.items():
        content = content.replace(f"{{{{{key}}}}}", str(value))
    return content


def generate_vba_for_survey_check(alignment: str, chainage_start: float, chainage_end: float) -> str:
    """Generate a VBA script for survey check using live data from SQLite."""
    df = query_chainages(alignment=alignment, ch_start=chainage_start, ch_end=chainage_end)
    if df.empty:
        return "No chainages found for the given criteria."
    chainage_list = sorted(df["chainage"].unique())
    placeholders = {
        "ALIGNMENT_NAME": alignment,
        "CHAINAGE_LIST": ", ".join([str(round(c, 3)) for c in chainage_list]),
    }
    return generate_vba_from_template("survey_check", placeholders)


def generate_all_vba_scripts(chainages, project_name="Project", calculations=None, alignment="Main_Line"):
    """Fill all four VBA templates using SQLite chainages/levels when live lists are empty."""
    from core.database import query_geometry

    if not chainages:
        df = query_chainages(alignment=alignment if alignment and alignment != "Main_Line" else None)
        chainages = sorted(df["chainage"].unique()) if not df.empty else []
    ch_list = ", ".join(str(round(float(c), 3)) for c in chainages) or "0"
    levels = []
    if calculations:
        first = next(iter(calculations.values()))
        lows = first.get("pr_low", {}) or first.get("pr_left_level", {})
        levels = [lows.get(c, 0) or 0 for c in chainages]
    if not levels:
        geom = query_geometry(alignment=alignment if alignment and alignment != "Main_Line" else None)
        if not geom.empty and "level" in geom.columns:
            by_ch = dict(zip(geom["chainage"], geom["level"].fillna(0)))
            levels = [by_ch.get(c, 0) or 0 for c in chainages]
        else:
            levels = [0] * len(chainages)
    lvl_list = ", ".join(str(round(float(v), 3)) for v in levels) or "0"
    common = {
        "ALIGNMENT_NAME": alignment or project_name,
        "CHAINAGE_LIST": ch_list,
        "LEVEL_LIST": lvl_list,
        "OFFSET": "1.435",
        "PROJECT_NAME": project_name,
    }
    scripts = {}
    for name in ("survey_check", "long_section", "cross_section", "chainage_labels"):
        scripts[name] = generate_vba_from_template(name, common)
    return scripts


def generate_vba_script(chainages=None, project_name="Project", alignment=None):
    scripts = generate_all_vba_scripts(chainages or [], project_name, alignment=alignment)
    return scripts.get("survey_check", "No template")


TOOLS = {
    "run_qa": {
        "func": run_compliance_checks,
        "description": "Run QA checks on a track. Input: track_data (dict), limits (dict), track_category (str), design_speed (float).",
    },
    "calculate_lift": {
        "func": calculate_lift,
        "description": "Calculate lift from existing and proposed levels. Input: existing_level (float), proposed_level (float).",
    },
    "parse_xml": {
        "func": parse_station_base,
        "description": "Parse a Station Base XML file (bytes) into a DataFrame.",
    },
    "import_dxf": {
        "func": SurveyImporter().import_dxf,
        "description": "Import DXF survey data (bytes) and return features and constraints.",
    },
    "write_excel": {
        "func": write_workbook,
        "description": "Write an Excel workbook from design data.",
    },
    "query_chainages": {
        "func": query_chainages,
        "description": "Query chainages from SQLite. Optional filters: alignment, type, ch_start, ch_end. Returns a DataFrame.",
    },
    "query_survey_features": {
        "func": query_survey_features,
        "description": "Query survey features from SQLite. Optional filters: category, ch_start, ch_end. Returns a DataFrame.",
    },
    "generate_vba_from_template": {
        "func": generate_vba_from_template,
        "description": "Generate a VBA script from a template. Input: template_name (str), placeholders (dict).",
    },
}