File size: 9,742 Bytes
14add0c
a977115
 
14add0c
9e7bcc4
 
 
 
 
 
 
 
0e66dad
 
 
9e7bcc4
a977115
14add0c
17b8d44
14add0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a977115
 
 
 
 
 
 
14add0c
 
 
 
 
 
 
 
 
a977115
 
 
 
 
 
 
 
0e66dad
17b8d44
 
a977115
 
 
0e66dad
 
 
 
a977115
 
0e66dad
 
 
 
a977115
 
 
0e66dad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e25afb
17b8d44
 
 
0e25afb
c31d423
 
 
 
 
0e25afb
9e7bcc4
 
 
0e25afb
d57dfb8
0e25afb
 
 
17b8d44
 
 
9e7bcc4
 
 
 
0e25afb
 
 
 
 
 
 
 
 
 
 
 
 
a977115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e7bcc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e66dad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a977115
14add0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e66dad
14add0c
97e7973
0e66dad
97e7973
0e66dad
14add0c
 
 
 
 
97e7973
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import logging
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from sqlalchemy.exc import OperationalError
from config import (
    DATABASE_URL,
    DEFAULT_LEADER_NAME,
    DEFAULT_LEADER_EMAIL,
    DEFAULT_LEADER_PASSWORD,
    DEFAULT_AUTHORITY_NAME,
    DEFAULT_AUTHORITY_EMAIL,
    DEFAULT_AUTHORITY_PASSWORD,
    DEFAULT_ADMIN_NAME,
    DEFAULT_ADMIN_EMAIL,
    DEFAULT_ADMIN_PASSWORD,
)

logger = logging.getLogger(__name__)

FALLBACK_SQLITE_URL = "sqlite:///./janshakti.db"


def _build_engine(url: str):
    """Create a SQLAlchemy engine for the given URL."""
    is_sqlite = url.startswith("sqlite")
    kwargs = {"pool_pre_ping": True}
    if is_sqlite:
        kwargs["connect_args"] = {"check_same_thread": False}
    else:
        kwargs["connect_args"] = {"connect_timeout": 10}
        kwargs["pool_recycle"] = 300
        kwargs["pool_size"] = 5
        kwargs["max_overflow"] = 10
    return create_engine(url, **kwargs), is_sqlite


# --- Build initial engine ---------------------------------------------------
_active_url = DATABASE_URL
engine, IS_SQLITE = _build_engine(_active_url)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


class Base(DeclarativeBase):
    pass


def _switch_to_sqlite():
    """Fall back to a local SQLite database when PostgreSQL is unreachable."""
    global engine, SessionLocal, IS_SQLITE, _active_url  # noqa: PLW0603
    print("[DB] ⚠️  PostgreSQL unreachable — falling back to local SQLite database")
    _active_url = FALLBACK_SQLITE_URL
    engine, IS_SQLITE = _build_engine(FALLBACK_SQLITE_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def _ensure_user_columns_sqlite():
    if not IS_SQLITE:
        return
    with engine.connect() as conn:
        result = conn.execute(text("PRAGMA table_info(users)"))
        columns = [row[1] for row in result.fetchall()]
        if "state" not in columns:
            conn.execute(text("ALTER TABLE users ADD COLUMN state VARCHAR"))
        if "district" not in columns:
            conn.execute(text("ALTER TABLE users ADD COLUMN district VARCHAR"))
        if "role" not in columns:
            conn.execute(text("ALTER TABLE users ADD COLUMN role VARCHAR NOT NULL DEFAULT 'citizen'"))
        if "is_active" not in columns:
            conn.execute(text("ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT 1"))
        if "last_login_at" not in columns:
            conn.execute(text("ALTER TABLE users ADD COLUMN last_login_at DATETIME"))
            conn.commit()


def _ensure_user_columns_postgres():
    if IS_SQLITE:
        return

    required_columns = {
        "state": "VARCHAR",
        "district": "VARCHAR",
        "role": "VARCHAR NOT NULL DEFAULT 'citizen'",
        "is_active": "BOOLEAN NOT NULL DEFAULT TRUE",
        "last_login_at": "TIMESTAMP WITH TIME ZONE",
    }

    with engine.connect() as conn:
        result = conn.execute(text(
            "SELECT column_name FROM information_schema.columns "
            "WHERE table_name = 'users'"
        ))
        existing = {row[0] for row in result.fetchall()}

        for name, col_type in required_columns.items():
            if name not in existing:
                conn.execute(text(f"ALTER TABLE users ADD COLUMN {name} {col_type}"))
                print(f"[DB] Added missing column: users.{name}")

        conn.commit()


def _ensure_complaint_workflow_columns():
    if not IS_SQLITE:
        return

    required_columns = {
        "ai_risk_score": "FLOAT",
        "ai_risk_level": "VARCHAR",
        "ai_risk_factors": "TEXT",
        "ai_risk_reasoning": "TEXT",
        "ai_leader_brief": "TEXT",
        "citizen_user_id": "INTEGER",
        "citizen_language": "VARCHAR",
        "image_path": "VARCHAR",
        "audio_path": "VARCHAR",
        "assigned_authority": "VARCHAR",
        "authority_email": "VARCHAR",
        "leader_note": "TEXT",
        "authority_response": "TEXT",
        "citizen_update": "TEXT",
        "ai_breakdown": "TEXT",
        "ai_explanation": "TEXT",
        "ai_model_version": "VARCHAR",
        "before_meta": "TEXT",
        "after_meta": "TEXT",
        "verification_score": "FLOAT",
        "verification_confidence": "FLOAT",
    }

    with engine.connect() as conn:
        result = conn.execute(text("PRAGMA table_info(complaints)"))
        columns = [row[1] for row in result.fetchall()]

        for name, col_type in required_columns.items():
            if name not in columns:
                conn.execute(text(f"ALTER TABLE complaints ADD COLUMN {name} {col_type}"))

        conn.commit()


def _seed_default_leader():
    from models.user import User
    from routers.auth import hash_password

    db = SessionLocal()
    try:
        existing = db.query(User).filter(User.email == DEFAULT_LEADER_EMAIL).first()
        if existing:
            if existing.role != "leader":
                existing.role = "leader"
                db.commit()
            return

        leader = User(
            name=DEFAULT_LEADER_NAME,
            email=DEFAULT_LEADER_EMAIL,
            phone=None,
            role="leader",
            hashed_password=hash_password(DEFAULT_LEADER_PASSWORD),
        )
        db.add(leader)
        db.commit()
        print(f"[Auth] Default leader ready: {DEFAULT_LEADER_EMAIL}")
    finally:
        db.close()


def _seed_default_authority():
    from models.user import User
    from routers.auth import hash_password

    db = SessionLocal()
    try:
        existing = db.query(User).filter(User.email == DEFAULT_AUTHORITY_EMAIL).first()
        if existing:
            if existing.role != "authority":
                existing.role = "authority"
                db.commit()
            return

        authority = User(
            name=DEFAULT_AUTHORITY_NAME,
            email=DEFAULT_AUTHORITY_EMAIL,
            phone=None,
            role="authority",
            hashed_password=hash_password(DEFAULT_AUTHORITY_PASSWORD),
        )
        db.add(authority)
        db.commit()
        print(f"[Auth] Default authority ready: {DEFAULT_AUTHORITY_EMAIL}")
    finally:
        db.close()


def _seed_default_admin():
    from models.user import User
    from routers.auth import hash_password

    db = SessionLocal()
    try:
        existing = db.query(User).filter(User.email == DEFAULT_ADMIN_EMAIL).first()
        if existing:
            changed = False
            if existing.role != "admin":
                existing.role = "admin"
                changed = True
            if existing.is_active is False:
                existing.is_active = True
                changed = True
            if changed:
                db.commit()
            return

        admin = User(
            name=DEFAULT_ADMIN_NAME,
            email=DEFAULT_ADMIN_EMAIL,
            phone=None,
            role="admin",
            hashed_password=hash_password(DEFAULT_ADMIN_PASSWORD),
            is_active=True,
        )
        db.add(admin)
        db.commit()
        print(f"[Auth] Default admin ready: {DEFAULT_ADMIN_EMAIL}")
    finally:
        db.close()


def init_db():
    """Initialize database tables. If PostgreSQL is unreachable,
    automatically fall back to a local SQLite database so the app
    can still start and serve requests."""
    try:
        Base.metadata.create_all(bind=engine)
    except (OperationalError, Exception) as exc:
        if not IS_SQLITE:
            print(f"[DB] PostgreSQL connection failed: {exc}")
            _switch_to_sqlite()
            # Retry with SQLite
            Base.metadata.create_all(bind=engine)
        else:
            raise

    try:
        if IS_SQLITE:
            _ensure_user_columns_sqlite()
            _ensure_complaint_workflow_columns()
        else:
            _ensure_user_columns_postgres()
            _ensure_pg_complaint_columns()
        _seed_default_admin()
        _seed_default_leader()
        _seed_default_authority()
        print(f"[DB] ✅ Database initialized successfully (using {'SQLite' if IS_SQLITE else 'PostgreSQL'})")
    except Exception as exc:
        print(f"[DB] Warning — seeding/migration issue (non-fatal): {exc}")


def _ensure_pg_complaint_columns():
    """Add any missing columns to the complaints table in PostgreSQL."""
    required_columns = {
        "ai_risk_score": "FLOAT",
        "ai_risk_level": "VARCHAR",
        "ai_risk_factors": "TEXT",
        "ai_risk_reasoning": "TEXT",
        "ai_leader_brief": "TEXT",
        "citizen_language": "VARCHAR",
        "image_path": "VARCHAR",
        "audio_path": "VARCHAR",
        "assigned_authority": "VARCHAR",
        "authority_email": "VARCHAR",
        "leader_note": "TEXT",
        "authority_response": "TEXT",
        "citizen_update": "TEXT",
        "ai_breakdown": "TEXT",
        "ai_explanation": "TEXT",
        "ai_model_version": "VARCHAR",
        "before_meta": "TEXT",
        "after_meta": "TEXT",
        "verification_score": "FLOAT",
        "verification_confidence": "FLOAT",
    }

    with engine.connect() as conn:
        result = conn.execute(text(
            "SELECT column_name FROM information_schema.columns "
            "WHERE table_name = 'complaints'"
        ))
        existing = {row[0] for row in result.fetchall()}

        for name, col_type in required_columns.items():
            if name not in existing:
                conn.execute(text(f"ALTER TABLE complaints ADD COLUMN {name} {col_type}"))
                print(f"[DB] Added missing column: complaints.{name}")

        conn.commit()