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
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
"""
SQLite database wrapper for structured track design data with traceability.
"""

import sqlite3
from pathlib import Path
from typing import Any, Dict, List, Optional

import pandas as pd

DB_PATH = Path(__file__).parent.parent / "data" / "track_design.db"


def get_connection():
    DB_PATH.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(DB_PATH))
    conn.row_factory = sqlite3.Row
    return conn


def init_db():
    conn = get_connection()
    cursor = conn.cursor()
    cursor.executescript(
        """
        CREATE TABLE IF NOT EXISTS chainages (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            alignment TEXT NOT NULL,
            chainage REAL NOT NULL,
            track_no INTEGER,
            type TEXT,
            level REAL,
            radius REAL,
            cant REAL,
            grade REAL,
            source_file TEXT,
            standard_clause TEXT,
            UNIQUE(alignment, chainage, type)
        );

        CREATE TABLE IF NOT EXISTS survey_features (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            layer TEXT,
            name TEXT,
            category TEXT,
            chainage REAL,
            clearance REAL,
            height REAL,
            description TEXT,
            geometry_json TEXT,
            source_file TEXT
        );

        CREATE TABLE IF NOT EXISTS drawings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            drawing_number TEXT UNIQUE,
            revision TEXT,
            title TEXT,
            status TEXT,
            checker TEXT,
            approver TEXT,
            chainage_start REAL,
            chainage_end REAL,
            issue_date TEXT,
            notes TEXT,
            source_file TEXT
        );

        CREATE TABLE IF NOT EXISTS psr (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            track_no INTEGER,
            speed_mph INTEGER,
            category TEXT,
            radius_min REAL,
            cant_def REAL,
            source_file TEXT,
            UNIQUE(track_no, speed_mph, category)
        );

        CREATE TABLE IF NOT EXISTS project_metadata (
            key TEXT PRIMARY KEY,
            value TEXT
        );

        CREATE TABLE IF NOT EXISTS provenance (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            entity_type TEXT NOT NULL,
            entity_id TEXT,
            source_file TEXT,
            chainage REAL,
            standard_clause TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        );

        CREATE INDEX IF NOT EXISTS idx_chainages_alignment ON chainages(alignment);
        CREATE INDEX IF NOT EXISTS idx_chainages_chainage ON chainages(chainage);
        CREATE INDEX IF NOT EXISTS idx_chainages_ch ON chainages(chainage);
        CREATE INDEX IF NOT EXISTS idx_chainages_type ON chainages(type);
        CREATE INDEX IF NOT EXISTS idx_survey_ch ON survey_features(chainage);
        CREATE INDEX IF NOT EXISTS idx_provenance_ch ON provenance(chainage);
        """
    )
    for stmt in (
        "ALTER TABLE chainages ADD COLUMN source_file TEXT",
        "ALTER TABLE chainages ADD COLUMN standard_clause TEXT",
        "ALTER TABLE survey_features ADD COLUMN source_file TEXT",
        "ALTER TABLE drawings ADD COLUMN source_file TEXT",
        "ALTER TABLE psr ADD COLUMN source_file TEXT",
    ):
        try:
            cursor.execute(stmt)
        except sqlite3.OperationalError:
            pass
    conn.commit()
    conn.close()


def log_provenance(
    entity_type: str,
    entity_id: str = None,
    source_file: str = None,
    chainage: float = None,
    standard_clause: str = None,
):
    conn = get_connection()
    conn.execute(
        """
        INSERT INTO provenance (entity_type, entity_id, source_file, chainage, standard_clause)
        VALUES (?, ?, ?, ?, ?)
        """,
        (entity_type, entity_id, source_file, chainage, standard_clause),
    )
    conn.commit()
    conn.close()


insert_provenance = log_provenance


def insert_chainages(
    df: pd.DataFrame,
    type_label: str,
    alignment: str = None,
    source_file: str = None,
    standard_clause: str = "NR/L2/TRK/2500",
):
    if df is None or df.empty:
        return
    conn = get_connection()
    cursor = conn.cursor()

    def _insert_row(align: str, row):
        ch = row.get("datum_chainage")
        if ch is None or pd.isna(ch):
            return
        radius = row.get("center_radius_m") or row.get("offset_radius_m")
        cant = row.get("center_cant_m") or row.get("offset_cant_m")
        level = row.get("level_m")
        grade = row.get("center_grade")
        cursor.execute(
            """
            INSERT OR REPLACE INTO chainages
            (alignment, chainage, type, level, radius, cant, grade, source_file, standard_clause)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                align,
                float(ch),
                type_label,
                None if level is None or pd.isna(level) else float(level),
                None if radius is None or pd.isna(radius) else float(radius),
                None if cant is None or pd.isna(cant) else float(cant),
                None if grade is None or pd.isna(grade) else float(grade),
                source_file,
                standard_clause,
            ),
        )
        cursor.execute(
            """
            INSERT INTO provenance (entity_type, entity_id, source_file, chainage, standard_clause)
            VALUES (?, ?, ?, ?, ?)
            """,
            ("chainage", f"{align}:{type_label}:{ch}", source_file, float(ch), standard_clause),
        )

    if alignment is None and "offset_alignment" in df.columns:
        for align, group in df.groupby("offset_alignment"):
            for _, row in group.iterrows():
                _insert_row(str(align), row)
    else:
        align = alignment or "Unknown"
        for _, row in df.iterrows():
            _insert_row(align, row)
    conn.commit()
    conn.close()


def insert_survey_features(features: List[Dict], source_file: str = None):
    if not features:
        return
    conn = get_connection()
    cursor = conn.cursor()
    for feat in features:
        cursor.execute(
            """
            INSERT INTO survey_features
            (layer, name, category, chainage, clearance, height, description, geometry_json, source_file)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                feat.get("layer"),
                feat.get("name"),
                feat.get("category"),
                feat.get("chainage"),
                feat.get("properties", {}).get("clearance") if isinstance(feat.get("properties"), dict) else None,
                feat.get("properties", {}).get("height") if isinstance(feat.get("properties"), dict) else None,
                feat.get("description", ""),
                str(feat.get("geometry", {})),
                source_file or feat.get("source_file"),
            ),
        )
        if feat.get("chainage") is not None:
            cursor.execute(
                """
                INSERT INTO provenance (entity_type, entity_id, source_file, chainage, standard_clause)
                VALUES (?, ?, ?, ?, ?)
                """,
                (
                    "survey",
                    feat.get("name"),
                    source_file,
                    feat.get("chainage"),
                    "survey/DXF",
                ),
            )
    conn.commit()
    conn.close()


def insert_drawing_metadata(drawing_data: Dict):
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute(
        """
        INSERT OR REPLACE INTO drawings
        (drawing_number, revision, title, status, checker, approver,
         chainage_start, chainage_end, issue_date, notes, source_file)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """,
        (
            drawing_data.get("number"),
            drawing_data.get("revision"),
            drawing_data.get("title"),
            drawing_data.get("status"),
            drawing_data.get("checker"),
            drawing_data.get("approver"),
            drawing_data.get("chainage_start"),
            drawing_data.get("chainage_end"),
            drawing_data.get("issue_date"),
            drawing_data.get("notes"),
            drawing_data.get("source_file"),
        ),
    )
    cursor.execute(
        """
        INSERT INTO provenance (entity_type, entity_id, source_file, chainage, standard_clause)
        VALUES (?, ?, ?, ?, ?)
        """,
        (
            "drawing",
            drawing_data.get("number") or drawing_data.get("title"),
            drawing_data.get("source_file"),
            drawing_data.get("chainage_start"),
            "drawing review",
        ),
    )
    conn.commit()
    conn.close()


def insert_psr_data(
    track_no: int,
    speed: int,
    category: str,
    radius_min: float,
    cant_def: float = 110,
    source_file: str = "manual",
):
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute(
        """
        INSERT OR REPLACE INTO psr (track_no, speed_mph, category, radius_min, cant_def, source_file)
        VALUES (?, ?, ?, ?, ?, ?)
        """,
        (track_no, speed, category, radius_min, cant_def, source_file),
    )
    cursor.execute(
        """
        INSERT INTO provenance (entity_type, entity_id, source_file, chainage, standard_clause)
        VALUES (?, ?, ?, ?, ?)
        """,
        ("psr", str(track_no), source_file, None, "NR/L2/TRK/2500 Section 5"),
    )
    conn.commit()
    conn.close()


def query_chainages(
    alignment: str = None,
    type_label: str = None,
    ch_start: float = None,
    ch_end: float = None,
) -> pd.DataFrame:
    conn = get_connection()
    query = "SELECT * FROM chainages WHERE 1=1"
    params: List[Any] = []
    if alignment:
        query += " AND alignment = ?"
        params.append(alignment)
    if type_label:
        query += " AND type = ?"
        params.append(type_label)
    if ch_start is not None:
        query += " AND chainage >= ?"
        params.append(ch_start)
    if ch_end is not None:
        query += " AND chainage <= ?"
        params.append(ch_end)
    df = pd.read_sql_query(query, conn, params=params)
    conn.close()
    return df


def query_survey_features(
    category: str = None, ch_start: float = None, ch_end: float = None
) -> pd.DataFrame:
    conn = get_connection()
    query = "SELECT * FROM survey_features WHERE 1=1"
    params: List[Any] = []
    if category:
        query += " AND category = ?"
        params.append(category)
    if ch_start is not None:
        query += " AND chainage >= ?"
        params.append(ch_start)
    if ch_end is not None:
        query += " AND chainage <= ?"
        params.append(ch_end)
    df = pd.read_sql_query(query, conn, params=params)
    conn.close()
    return df


def get_project_metadata(key: str) -> Optional[str]:
    conn = get_connection()
    row = conn.execute("SELECT value FROM project_metadata WHERE key = ?", (key,)).fetchone()
    conn.close()
    return row[0] if row else None


def set_project_metadata(key: str, value: str):
    conn = get_connection()
    conn.execute(
        "INSERT OR REPLACE INTO project_metadata (key, value) VALUES (?, ?)", (key, str(value))
    )
    conn.commit()
    conn.close()


def clear_project_data():
    conn = get_connection()
    cursor = conn.cursor()
    for table in (
        "chainages",
        "survey_features",
        "drawings",
        "psr",
        "project_metadata",
        "provenance",
    ):
        cursor.execute(f"DELETE FROM {table}")
    conn.commit()
    conn.close()


def query_geometry(alignment: str = None) -> pd.DataFrame:
    """Query geometry data for long sections (levels, grades, radii)."""
    conn = get_connection()
    try:
        query = "SELECT chainage, level, radius, cant, grade FROM chainages WHERE 1=1"
        params = []
        if alignment:
            query += " AND alignment = ?"
            params.append(alignment)
        query += " ORDER BY chainage"
        return pd.read_sql_query(query, conn, params=params)
    except Exception:
        return pd.DataFrame()
    finally:
        conn.close()


init_db()



def query_chainage_at(chainage: float, alignment: str = None) -> dict:
    """Fetch a single chainage row exactly (or nearest) from SQLite."""
    conn = get_connection()
    query = "SELECT * FROM chainages WHERE ABS(chainage - ?) < 0.01"
    params = [chainage]
    if alignment:
        query += " AND alignment = ?"
        params.append(alignment)
    cur = conn.execute(query, params)
    row = cur.fetchone()
    conn.close()
    if row:
        # Convert sqlite3.Row to dict
        return {k: row[k] for k in row.keys()}
    return None