Spaces:
Sleeping

File size: 35,160 Bytes
4199395
adc90ec
f54a7da
 
 
adc90ec
 
 
 
 
 
 
 
 
 
f8eb14a
 
f54a7da
f8eb14a
f54a7da
f8eb14a
 
 
 
 
f54a7da
 
196feb7
 
4199395
f54a7da
 
f8eb14a
 
 
f54a7da
f8eb14a
 
 
 
f54a7da
f8eb14a
 
 
 
 
 
 
4199395
 
 
 
 
 
f54a7da
20973a6
f54a7da
f8eb14a
 
 
 
 
f54a7da
6459e15
adc90ec
aa94889
 
f8eb14a
f54a7da
f8eb14a
f54a7da
f8eb14a
 
 
 
 
 
f54a7da
4199395
f54a7da
4199395
 
 
f54a7da
4199395
 
 
f54a7da
f8eb14a
f54a7da
aa94889
f54a7da
e05f029
f8eb14a
 
 
 
 
f54a7da
f8eb14a
f54a7da
f8eb14a
 
 
 
 
f8d4d80
f8eb14a
 
f54a7da
f8eb14a
f54a7da
196feb7
f8eb14a
 
 
f54a7da
196feb7
f54a7da
bcb5724
 
 
 
 
 
 
f54a7da
 
 
196feb7
 
4199395
 
 
196feb7
 
f54a7da
adc90ec
f54a7da
 
 
 
 
 
 
 
 
 
adc90ec
 
 
 
f54a7da
 
adc90ec
 
 
 
f54a7da
 
 
 
 
 
196feb7
f8eb14a
 
f54a7da
adc90ec
f54a7da
 
 
 
adc90ec
 
 
 
 
f54a7da
f8eb14a
f54a7da
f8eb14a
 
f54a7da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8eb14a
 
 
f54a7da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8eb14a
 
 
f54a7da
 
 
 
 
adc90ec
 
 
 
 
 
f54a7da
adc90ec
 
 
f54a7da
20973a6
f54a7da
 
 
 
 
adc90ec
 
f54a7da
 
20973a6
f54a7da
20973a6
adc90ec
 
 
 
 
 
 
 
 
 
 
f54a7da
 
 
 
 
 
 
 
 
 
 
adc90ec
 
f54a7da
 
 
 
adc90ec
f54a7da
 
 
 
adc90ec
f54a7da
 
 
 
 
 
 
 
 
 
 
 
 
adc90ec
 
f54a7da
f8eb14a
adc90ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20973a6
f8eb14a
 
f54a7da
adc90ec
 
 
 
f54a7da
 
 
 
 
 
 
f8eb14a
 
f54a7da
 
 
 
 
adc90ec
 
 
 
 
 
 
f54a7da
 
 
 
 
aa94889
f54a7da
 
 
aa94889
af12ed2
 
f54a7da
af12ed2
f54a7da
6459e15
f54a7da
 
af12ed2
 
 
f54a7da
aa94889
f54a7da
 
 
 
aa94889
 
 
 
f54a7da
 
 
 
 
aa94889
 
 
 
f54a7da
 
 
aa94889
f54a7da
aa94889
 
f54a7da
1b33b49
f54a7da
 
aa94889
 
 
 
f54a7da
1b33b49
f54a7da
aa94889
f54a7da
 
aa94889
f54a7da
 
aa94889
 
f54a7da
 
aa94889
 
 
 
 
 
f54a7da
 
 
 
 
 
 
 
1b33b49
f54a7da
1b33b49
 
f54a7da
 
 
1b33b49
f54a7da
1b33b49
aa94889
f54a7da
 
 
20973a6
adc90ec
20973a6
f54a7da
20973a6
 
 
 
f54a7da
adc90ec
 
f54a7da
 
 
20973a6
 
adc90ec
 
 
 
 
f54a7da
aa94889
f54a7da
1b33b49
f54a7da
 
 
aa94889
f54a7da
aa94889
 
 
 
 
f54a7da
 
 
 
 
4199395
 
 
adc90ec
4199395
adc90ec
f54a7da
 
 
 
 
 
 
 
4199395
f54a7da
20973a6
4199395
 
f54a7da
adc90ec
 
f54a7da
adc90ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e37f85c
f54a7da
 
 
adc90ec
 
 
20973a6
 
4199395
20973a6
 
 
 
e37f85c
20973a6
 
 
 
 
f54a7da
20973a6
4199395
 
20973a6
adc90ec
f54a7da
 
 
 
20973a6
 
 
e37f85c
4199395
20973a6
4199395
 
9f9a9da
20973a6
 
 
adc90ec
20973a6
 
f54a7da
 
 
 
 
196feb7
4199395
f54a7da
 
 
 
 
196feb7
f54a7da
adc90ec
 
 
 
 
f54a7da
 
 
 
 
196feb7
f54a7da
 
196feb7
 
f54a7da
 
 
196feb7
 
 
538d4ed
f54a7da
 
 
 
 
 
 
 
 
 
 
20973a6
f54a7da
 
20973a6
f54a7da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196feb7
f54a7da
 
 
 
20973a6
f54a7da
 
 
 
 
 
 
 
196feb7
f54a7da
196feb7
f54a7da
 
 
f8eb14a
 
196feb7
f8eb14a
f54a7da
 
 
f8eb14a
890592f
f8eb14a
f54a7da
 
f8eb14a
adc90ec
 
 
f8eb14a
f54a7da
f8eb14a
adc90ec
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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# LedgerSG Full-Stack Dockerfile
# Optimized for Hugging Face Spaces (Single-Stage, Single-File)
# Database: PostgreSQL 17 + Redis (localhost:6379)
# Frontend: Next.js Standalone Mode
# Backend: Django + Gunicorn (Production WSGI)
# 
# FIXES APPLIED:
# 1. Log path consistency (boot.py matches entrypoint.sh)
# 2. Schema idempotency (only applies on first run)
# 3. Health check timeout (120s for full startup)
# 4. Django settings module export (before Gunicorn)
# 5. Frontend chunk validation (minimum 20 chunks)
# 6. Backend process death detection
# 7. Netcat availability verification
#
FROM python:3.13-trixie

# ═══════════════════════════════════════════════════════════════════════════════
# 1. Environment Configuration
# ═══════════════════════════════════════════════════════════════════════════════
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PIP_NO_CACHE_DIR=1
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
ENV DEBIAN_FRONTEND=noninteractive

# Service Ports (all exposed for flexible HF Space mapping)
ENV APP_PORT=7860
ENV FRONTEND_PORT=3000
ENV BACKEND_PORT=8000

# Runtime directories
ENV XDG_RUNTIME_DIR=/tmp/runtime-user
ENV PATH="/home/user/.local/bin:/usr/local/bin:${PATH}"

# PostgreSQL Configuration (persistent & user-writable)
ENV PGDATA=/data/postgresql
ENV PGHOST=/tmp
ENV PGPORT=5432

# Database Configuration
ENV DB_NAME=ledgersg_dev
ENV DB_USER=ledgersg
ENV DB_PASSWORD=ledgersg_secret_to_change
ENV DB_HOST=localhost
ENV DB_PORT=5432
ENV REDIS_URL=redis://localhost:6379/0

# Frontend Configuration for Backend API Integration
ENV NEXT_PUBLIC_API_URL=http://localhost:8000
ENV NEXT_OUTPUT_MODE=standalone
ENV NODE_ENV=production
ENV HOSTNAME=0.0.0.0

# ═══════════════════════════════════════════════════════════════════════════════
# 2. System Dependencies (Database + Dev Tools + netcat for port checking)
# ═══════════════════════════════════════════════════════════════════════════════
RUN apt-get update && apt-get install -y \
    bash coreutils ca-certificates cron curl wget git less procps sudo vim tar zip unzip tmux openssh-client rsync \
    build-essential gcc gnupg cmake pkg-config \
    libpq-dev libjson-c-dev libssl-dev libwebsockets-dev \
    libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz0b libffi-dev libjpeg-dev libopenjp2-7-dev \
    postgresql postgresql-contrib redis-server netcat-openbsd \
    && apt-get clean && rm -rf /var/lib/apt/lists/* \
    # Verify PostgreSQL installation at build time
    && if [ ! -d "/usr/lib/postgresql/17" ]; then echo "ERROR: PostgreSQL 17 not installed" && exit 1; fi \
    && echo "βœ“ PostgreSQL 17 verified at build time"

# ═══════════════════════════════════════════════════════════════════════════════
# 3. Toolchain Installation (UV, Bun)
# ═══════════════════════════════════════════════════════════════════════════════
RUN cd /usr/bin && \
    wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/bun && \
    wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/uv && \
    wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/uvx && \
    chmod a+x /usr/bin/bun /usr/bin/uv*

# ═══════════════════════════════════════════════════════════════════════════════
# 4. Python Virtual Environment & Dependencies
# ═══════════════════════════════════════════════════════════════════════════════
RUN python3 -m venv /opt/venv && \
    /opt/venv/bin/pip install --upgrade pip

# Install Python dependencies (includes gunicorn)
RUN /opt/venv/bin/pip install django-celery-beat && \
    /opt/venv/bin/pip install -U django djangorestframework djangorestframework-simplejwt django-cors-headers django-filter && \
    /opt/venv/bin/pip install psycopg[binary] celery[redis] redis py-moneyed pydantic weasyprint lxml python-decouple whitenoise gunicorn structlog sentry-sdk[django] argon2-cffi pytest pytest-django pytest-cov pytest-xdist model-bakery factory-boy faker httpx ruff mypy django-stubs djangorestframework-stubs pre-commit ipython django-debug-toolbar django-extensions && \
    /opt/venv/bin/pip install fastapi uvicorn httpx pydantic python-multipart sqlalchemy alembic aiofiles jinja2

# ═══════════════════════════════════════════════════════════════════════════════
# 5. Node.js Installation (LTS 24.x)
# ═══════════════════════════════════════════════════════════════════════════════
RUN curl -fsSL https://deb.nodesource.com/setup_24.x | bash - && \
    apt-get install -y nodejs && \
    rm -rf /var/lib/apt/lists/* && \
    node --version && \
    npm --version

# ═══════════════════════════════════════════════════════════════════════════════
# 6. User & Permission Setup (Hugging Face Requirement)
# ═══════════════════════════════════════════════════════════════════════════════
RUN groupadd -g 1000 user && \
    useradd -m -u 1000 -g user -d /home/user user && \
    echo "user ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/user && \
    chmod 0440 /etc/sudoers.d/user && \
    mkdir -p ${XDG_RUNTIME_DIR} /data /app /var/run/postgresql /data/postgresql && \
    chown -R user:user ${XDG_RUNTIME_DIR} /opt/venv /data /app /var/run/postgresql /var/lib/postgresql && \
    chmod 700 /data/postgresql

# ═══════════════════════════════════════════════════════════════════════════════
# 7. Global NPM & Playwright
# ═══════════════════════════════════════════════════════════════════════════════
RUN npm install -g --omit=dev pnpm@latest vite@latest vitest@latest serve && \
    npx playwright install chromium && \
    npx playwright install-deps chromium

# ═══════════════════════════════════════════════════════════════════════════════
# 8. Clone LedgerSG Repository (AT BUILD TIME)
# ═══════════════════════════════════════════════════════════════════════════════
RUN cd /app && \
    git clone https://github.com/nordeim/ledgersg.git ledgersg_src && \
    mv ledgersg_src/* . && \
    mv ledgersg_src/.* . 2>/dev/null || true && \
    rm -rf ledgersg_src && \
    chown -R user:user /app

# ═══════════════════════════════════════════════════════════════════════════════
# 9. Frontend Build (AT BUILD TIME - Standalone Mode)
# ═══════════════════════════════════════════════════════════════════════════════
RUN cd /app/apps/web && \
    npm install && \
    npm run clean && \
    NEXT_OUTPUT_MODE=standalone NEXT_PUBLIC_API_URL=http://localhost:8000 npm run build:server && \
    ls -la .next/standalone/ && \
    chown -R user:user /app/apps/web

# ═══════════════════════════════════════════════════════════════════════════════
# 10. Verify Frontend Build Integrity (FIX #5: Minimum 20 chunks)
# ═══════════════════════════════════════════════════════════════════════════════
RUN cd /app/apps/web && \
    echo "Verifying standalone build..." && \
    if [ ! -f ".next/standalone/server.js" ]; then \
        echo "ERROR: Frontend standalone build missing!"; \
        ls -la .next/ 2>&1 || true; \
        exit 1; \
    fi && \
    if [ ! -d ".next/standalone/.next/static" ]; then \
        echo "WARNING: Static files not in standalone folder, copying..."; \
        cp -r .next/static .next/standalone/.next/ || { \
            echo "ERROR: Failed to copy static files"; \
            exit 1; \
        }; \
    fi && \
    STATIC_COUNT=$(ls .next/standalone/.next/static/chunks/*.js 2>/dev/null | wc -l) && \
    if [ "$STATIC_COUNT" -lt 20 ]; then \
        echo "ERROR: Only $STATIC_COUNT JS chunks found. Expected 20+"; \
        exit 1; \
    fi && \
    echo "βœ“ Standalone build verified: $STATIC_COUNT JS chunks" && \
    chown -R user:user /app/apps/web

# ═══════════════════════════════════════════════════════════════════════════════
# 11. Database & Server Bootstrap Scripts (Embedded)
# ═══════════════════════════════════════════════════════════════════════════════
RUN mkdir -p /app/core /app/scripts && \
    chown -R user:user /app

# Enhanced boot.py - Keep-alive + Service Health Monitor + Log Viewer
# FIX #1: Log paths now match entrypoint.sh output locations
COPY <<'BOOTEOF' /app/core/boot.py
"""
LedgerSG HF Space Keep-Alive Server
Provides health checks, service monitoring, and log access for debugging

Log Files (all written by entrypoint.sh):
- /tmp/backend.log      β†’ Gunicorn stdout/stderr (combined)
- /tmp/frontend.log     β†’ Next.js server output
- /tmp/postgres.log     β†’ PostgreSQL server log
"""
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse, JSONResponse
import uvicorn
import os
import subprocess
import urllib.request
import urllib.error
from datetime import datetime

app = FastAPI(title="LedgerSG Space Monitor")

def check_service(url: str, timeout: int = 2) -> dict:
    """Check if a service is responding"""
    try:
        with urllib.request.urlopen(url, timeout=timeout) as response:
            return {
                "status": "healthy",
                "status_code": response.status,
                "url": url
            }
    except urllib.error.HTTPError as e:
        return {
            "status": "error",
            "error": f"HTTP {e.code}",
            "url": url
        }
    except Exception as e:
        return {
            "status": "error",
            "error": str(e),
            "url": url
        }

@app.get("/")
def read_root():
    """Complete service status overview"""
    return {
        "service": "LedgerSG HF Space",
        "status": "alive",
        "timestamp": datetime.now().isoformat(),
        "services": {
            "frontend": check_service("http://localhost:3000"),
            "backend": check_service("http://localhost:8000/api/v1/health/"),
            "boot": {"status": "healthy", "port": 7860}
        },
        "endpoints": {
            "health": "/health",
            "logs": "/logs/{service}?lines=50",
            "status": "/"
        }
    }

@app.get("/health")
def health():
    """Simple health check for container orchestration"""
    return {"status": "healthy", "service": "ledgersg-boot"}

@app.get("/logs/{service}")
def get_logs(service: str, lines: int = 50):
    """
    View service logs for debugging
    
    FIX #1: All log paths now match entrypoint.sh output locations
    """
    # CORRECTED: All paths match what entrypoint.sh actually creates
    log_files = {
        "backend": "/tmp/backend.log",           # ← Gunicorn combined output
        "frontend": "/tmp/frontend.log",         # ← Next.js output
        "postgres": "/tmp/postgres.log",         # ← PostgreSQL output
    }
    
    if service not in log_files:
        return JSONResponse(
            status_code=404,
            content={
                "error": "Unknown service",
                "available_services": list(log_files.keys()),
                "hint": f"Try: {', '.join(log_files.keys())}"
            }
        )
    
    log_path = log_files[service]
    
    # Check if log file exists
    if not os.path.exists(log_path):
        return JSONResponse(
            status_code=404,
            content={
                "error": "Log file not found",
                "log_path": log_path,
                "hint": "Service may not have started yet, or logging not enabled"
            }
        )
    
    try:
        result = subprocess.run(
            ["tail", f"-{lines}", log_path],
            capture_output=True,
            text=True,
            timeout=5
        )
        return {
            "service": service,
            "log_file": log_path,
            "lines_requested": lines,
            "lines_returned": len(result.stdout.strip().split('\n')) if result.stdout.strip() else 0,
            "content": result.stdout if result.stdout.strip() else "(log file is empty)"
        }
    except subprocess.TimeoutExpired:
        return JSONResponse(
            status_code=500,
            content={"error": "Timeout reading log file", "log_path": log_path}
        )
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={"error": str(e), "log_path": log_path}
        )

@app.get("/env")
def show_env():
    """Show relevant environment variables (safe for debugging)"""
    return {
        "APP_PORT": os.getenv("APP_PORT"),
        "FRONTEND_PORT": os.getenv("FRONTEND_PORT"),
        "BACKEND_PORT": os.getenv("BACKEND_PORT"),
        "NEXT_PUBLIC_API_URL": os.getenv("NEXT_PUBLIC_API_URL"),
        "DB_NAME": os.getenv("DB_NAME"),
        "DB_HOST": os.getenv("DB_HOST"),
        "DB_PORT": os.getenv("DB_PORT"),
        "NODE_ENV": os.getenv("NODE_ENV"),
        "PGDATA": os.getenv("PGDATA"),
    }

@app.get("/debug/info")
def debug_info():
    """Extended debugging information"""
    import sys
    
    # Check log files exist
    log_status = {}
    for service, path in {
        "backend": "/tmp/backend.log",
        "frontend": "/tmp/frontend.log",
        "postgres": "/tmp/postgres.log",
    }.items():
        if os.path.exists(path):
            stat = os.stat(path)
            log_status[service] = {
                "exists": True,
                "size_bytes": stat.st_size,
                "path": path
            }
        else:
            log_status[service] = {
                "exists": False,
                "path": path
            }
    
    return {
        "python_version": sys.version,
        "cwd": os.getcwd(),
        "logs": log_status,
        "env_ports": {
            "app": os.getenv("APP_PORT"),
            "frontend": os.getenv("FRONTEND_PORT"),
            "backend": os.getenv("BACKEND_PORT"),
        }
    }

if __name__ == "__main__":
    port = int(os.getenv("APP_PORT", 7860))
    print(f"Starting LedgerSG boot server on port {port}")
    print(f"Log endpoints available at:")
    print(f"  - GET /logs/backend")
    print(f"  - GET /logs/frontend")
    print(f"  - GET /logs/postgres")
    uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
BOOTEOF

# ═══════════════════════════════════════════════════════════════════════════════
# 12. Entrypoint Script (Runtime Service Orchestration)
# ═══════════════════════════════════════════════════════════════════════════════
COPY <<'ENTRYEOF' /usr/local/bin/entrypoint.sh
#!/bin/bash
set -e
echo "════════════════════════════════════════════════════════════════"
echo "   LedgerSG HF Space Starting"
echo "════════════════════════════════════════════════════════════════"
echo "πŸ• Startup time: $(date -Iseconds)"

# ═══════════════════════════════════════════════════════════════════════════════
# FIX #7: Verify netcat availability before use
# ═══════════════════════════════════════════════════════════════════════════════
if ! command -v nc &> /dev/null; then
    echo "⚠ WARNING: netcat not available, port checks will fail"
fi

# ═══════════════════════════════════════════════════════════════════════════════
# PostgreSQL Detection & Setup
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo "πŸ” Configuring PostgreSQL..."
PG_VERSION="17"
PG_BIN="/usr/lib/postgresql/${PG_VERSION}/bin"
if [ ! -d "/usr/lib/postgresql/${PG_VERSION}" ]; then
    echo "βœ— ERROR: PostgreSQL ${PG_VERSION} not found"
    ls -la /usr/lib/postgresql/ 2>&1 || echo "  (directory not accessible)"
    exit 1
fi
echo "βœ“ PostgreSQL ${PG_VERSION} at ${PG_BIN}"

# Verify binaries
for cmd in initdb pg_ctl psql pg_isready; do
    if [ ! -x "${PG_BIN}/${cmd}" ]; then
        echo "βœ— ERROR: ${cmd} not found"
        exit 1
    fi
done
echo "βœ“ All PostgreSQL binaries verified"

# Environment setup
mkdir -p $PGDATA
chown -R user:user $PGDATA
chmod 700 $PGDATA
mkdir -p /var/run/postgresql
chown -R user:user /var/run/postgresql
chmod 777 /var/run/postgresql

# Initialize PostgreSQL if needed
if [ ! -f "$PGDATA/PG_VERSION" ]; then
    echo "πŸ“¦ Initializing PostgreSQL cluster..."
    sudo -u user ${PG_BIN}/initdb -D $PGDATA
    cat >> $PGDATA/pg_hba.conf << 'PGHBA'
local   all             all                                     trust
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5
PGHBA
    echo "listen_addresses = 'localhost'" >> $PGDATA/postgresql.conf
    echo "port = 5432" >> $PGDATA/postgresql.conf
    echo "βœ“ PostgreSQL initialized"
else
    echo "βœ“ PostgreSQL cluster exists"
fi

# ═══════════════════════════════════════════════════════════════════════════════
# Start Redis
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo "πŸš€ Starting Redis on port 6379..."
redis-server --daemonize yes
sleep 1

# ═══════════════════════════════════════════════════════════════════════════════
# Start PostgreSQL
# ═══════════════════════════════════════════════════════════════════════════════
echo "πŸš€ Starting PostgreSQL on port 5432..."
sudo -u user ${PG_BIN}/pg_ctl -D $PGDATA -l /tmp/postgres.log start
echo "⏳ Waiting for PostgreSQL..."
for i in {1..30}; do
    if sudo -u user ${PG_BIN}/pg_isready -h localhost -p 5432 > /dev/null 2>&1; then
        echo "βœ“ PostgreSQL ready (attempt $i)"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "βœ— PostgreSQL failed to start"
        cat /tmp/postgres.log 2>/dev/null || echo "  (log not available)"
        exit 1
    fi
    sleep 1
done

# ═══════════════════════════════════════════════════════════════════════════════
# Create Database User and Database
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo "πŸ—„οΈ  Setting up database..."
if ! sudo -u user ${PG_BIN}/psql -h localhost -p 5432 -d postgres -c "SELECT 1 FROM pg_roles WHERE rolname='${DB_USER}';" | grep -q 1; then
    echo "  β†’ Creating user: ${DB_USER}"
    sudo -u user ${PG_BIN}/psql -h localhost -p 5432 -d postgres -c "CREATE ROLE ${DB_USER} WITH LOGIN CREATEDB PASSWORD '${DB_PASSWORD}';"
else
    echo "  βœ“ User ${DB_USER} exists"
fi

if ! sudo -u user ${PG_BIN}/psql -h localhost -p 5432 -d postgres -c "SELECT 1 FROM pg_database WHERE datname='${DB_NAME}';" | grep -q 1; then
    echo "  β†’ Creating database: ${DB_NAME}"
    sudo -u user ${PG_BIN}/psql -h localhost -p 5432 -d postgres -c "CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};"
else
    echo "  βœ“ Database ${DB_NAME} exists"
fi

sudo -u user ${PG_BIN}/psql -h localhost -p 5432 -d ${DB_NAME} -c "GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};"
echo "βœ“ Database setup complete"

# ═══════════════════════════════════════════════════════════════════════════════
# FIX #2: Apply Schema ONLY if tables don't exist (IDEMPOTENT)
# ═══════════════════════════════════════════════════════════════════════════════
echo "  β†’ Checking database schema..."
TABLE_COUNT=$(sudo -u user ${PG_BIN}/psql -h localhost -p 5432 -d ${DB_NAME} -t -c \
    "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema IN ('core','coa','gst','journal','invoicing','banking','audit');" 2>/dev/null | tr -d ' ' || echo "0")

if [ -z "$TABLE_COUNT" ] || [ "$TABLE_COUNT" -eq "0" ]; then
    echo "  β†’ Applying database schema (first run)..."
    echo "  ⚠️  WARNING: This schema uses DROP SCHEMA IF EXISTS... CASCADE"
    echo "      Re-running the schema will DESTROY all existing data!"
    sudo -u user ${PG_BIN}/psql -h localhost -p 5432 -d ${DB_NAME} -f /app/apps/backend/database_schema.sql
    echo "  βœ“ Schema applied"
else
    echo "  βœ“ Database schema already exists ($TABLE_COUNT tables found)"
    echo "  ℹ️  Skipping schema application to preserve data"
    echo ""
    echo "  ⚠️  TO RE-APPLY SCHEMA (DATA WILL BE LOST):"
    echo "      1. Backup your data first!"
    echo "      2. Drop the database: DROP DATABASE ${DB_NAME};"
    echo "      3. Container will auto-apply schema on next startup"
fi

# ═══════════════════════════════════════════════════════════════════════════════
# Verify Redis
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo "πŸ” Verifying Redis..."
if redis-cli ping > /dev/null 2>&1; then
    echo "βœ“ Redis ready on localhost:6379"
else
    echo "βœ— Redis failed to start"
    exit 1
fi

# ═══════════════════════════════════════════════════════════════════════════════
# Start Backend API (Django + Gunicorn - Production Ready)
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo "πŸš€ Starting Backend API (Gunicorn) on port ${BACKEND_PORT}..."
cd /app/apps/backend

# Create .env file for backend
# FIX #4: Include DJANGO_SETTINGS_MODULE in .env file
cat > .env << ENVEOF
DJANGO_SETTINGS_MODULE=config.settings.service
DEBUG=False
SECRET_KEY=django-secret-key-for-hf-space-$(date +%s)
DB_NAME=${DB_NAME}
DB_USER=${DB_USER}
DB_PASSWORD=${DB_PASSWORD}
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
REDIS_URL=${REDIS_URL}
ALLOWED_HOSTS=localhost,127.0.0.1,0.0.0.0
CORS_ALLOWED_ORIGINS=http://localhost:${FRONTEND_PORT},http://127.0.0.1:${FRONTEND_PORT}
LOG_LEVEL=INFO
ENVEOF

# Start Django with Gunicorn (production WSGI)
# FIX #4: Export DJANGO_SETTINGS_MODULE before Gunicorn starts
# FIX #1: Using /tmp/backend.log for all logs (matches boot.py)
sudo -u user nohup bash -c "
export DJANGO_SETTINGS_MODULE=config.settings.service &&
source /opt/venv/bin/activate &&
cd /app/apps/backend &&
gunicorn config.wsgi:application \
-b 0.0.0.0:${BACKEND_PORT} \
--workers 2 \
--threads 2 \
--worker-class gthread \
--timeout 60 \
--keep-alive 5 \
--max-requests 1000 \
--max-requests-jitter 50 \
--access-logfile - \
--error-logfile - \
--capture-output \
--enable-stdio-inheritance
" > /tmp/backend.log 2>&1 &
BACKEND_PID=$!
echo "βœ“ Backend PID: ${BACKEND_PID} (Gunicorn: 2 workers, 2 threads)"

# ═══════════════════════════════════════════════════════════════════════════════
# FIX #6: Wait for backend with process death detection
# ═══════════════════════════════════════════════════════════════════════════════
echo "⏳ Waiting for Backend API..."
BACKEND_READY=false
for i in {1..60}; do
    # Check if Gunicorn process died (CRITICAL FIX)
    if ! pgrep -f "gunicorn.*config.wsgi" > /dev/null 2>&1; then
        echo "βœ— Backend Gunicorn process died (attempt $i)"
        echo "πŸ“‹ Backend error log:"
        tail -50 /tmp/backend.log 2>/dev/null || echo "  (log not available)"
        break
    fi
    
    # Check health endpoint
    if curl -sf http://localhost:${BACKEND_PORT}/api/v1/health/ > /dev/null 2>&1; then
        echo "βœ“ Backend API ready (attempt $i)"
        BACKEND_READY=true
        break
    fi
    
    # Fallback: check if port is listening (uses netcat)
    if nc -z localhost ${BACKEND_PORT} 2>/dev/null; then
        echo "βœ“ Backend port listening (attempt $i)"
        break
    fi
    
    if [ $i -eq 30 ]; then
        echo "⚠ Backend not ready after 30s, checking logs..."
        tail -30 /tmp/backend.log 2>/dev/null || true
    fi
    
    sleep 1
done

if [ "$BACKEND_READY" = false ]; then
    echo "⚠ Backend API may not be fully ready (continuing)"
    echo "πŸ“‹ Last 50 lines of error log:"
    tail -50 /tmp/backend.log 2>/dev/null || echo "  (log not available)"
fi

# ═══════════════════════════════════════════════════════════════════════════════
# Start Frontend (Next.js Standalone)
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo "πŸš€ Starting Frontend on port ${FRONTEND_PORT}..."
cd /app/apps/web

# Verify build integrity
if [ ! -f ".next/standalone/server.js" ]; then
    echo "βœ— ERROR: Frontend standalone build missing!"
    exit 1
fi

sudo -u user nohup bash -c "
export NODE_ENV=production
export PORT=${FRONTEND_PORT}
export HOSTNAME=0.0.0.0
export NEXT_PUBLIC_API_URL=http://localhost:8000
node .next/standalone/server.js
" > /tmp/frontend.log 2>&1 &
FRONTEND_PID=$!
echo "βœ“ Frontend PID: ${FRONTEND_PID}"

# Wait for frontend
for i in {1..30}; do
    if curl -s http://localhost:${FRONTEND_PORT} > /dev/null 2>&1; then
        echo "βœ“ Frontend ready (attempt $i)"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "⚠ Frontend may not be ready (continuing)"
        tail -20 /tmp/frontend.log 2>/dev/null || true
    fi
    sleep 1
done

# ═══════════════════════════════════════════════════════════════════════════════
# Final Service Status
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo "════════════════════════════════════════════════════════════════"
echo "   Service Status Summary"
echo "════════════════════════════════════════════════════════════════"
echo "πŸ• Ready at: $(date -Iseconds)"
echo ""

SERVICES_READY=true
if [ "$BACKEND_READY" = true ]; then
    echo "  βœ… Backend API:    http://localhost:${BACKEND_PORT} (Gunicorn)"
else
    echo "  ⚠️  Backend API:    Not responding (check logs with: curl http://localhost:${APP_PORT}/logs/backend)"
    SERVICES_READY=false
fi

if curl -s http://localhost:${FRONTEND_PORT} > /dev/null 2>&1; then
    echo "  βœ… Frontend:       http://localhost:${FRONTEND_PORT}"
else
    echo "  ⚠️  Frontend:       Not responding"
    SERVICES_READY=false
fi

if redis-cli ping > /dev/null 2>&1; then
    echo "  βœ… Redis:          localhost:6379"
else
    echo "  ⚠️  Redis:          Not responding"
fi

if sudo -u user ${PG_BIN}/pg_isready -h localhost -p 5432 > /dev/null 2>&1; then
    echo "  βœ… PostgreSQL:     localhost:5432"
else
    echo "  ⚠️  PostgreSQL:     Not responding"
fi

echo "  ℹ️  Monitor:        http://localhost:${APP_PORT} (boot.py)"
echo ""

if [ "$SERVICES_READY" = true ]; then
    echo "πŸŽ‰ All critical services are ready!"
else
    echo "⚠️  Some services still starting... Check logs at: http://localhost:${APP_PORT}/logs/{service}"
fi

echo ""
echo "πŸ“– Debug commands:"
echo "  β€’ Full status:  curl http://localhost:${APP_PORT}/"
echo "  β€’ Health:       curl http://localhost:${APP_PORT}/health"
echo "  β€’ Logs:         curl http://localhost:${APP_PORT}/logs/backend"
echo "  β€’ Frontend:     curl http://localhost:${APP_PORT}/logs/frontend"
echo ""
echo "════════════════════════════════════════════════════════════════"

# Execute the main command (boot.py keep-alive server)
exec sudo -u user "$@"
ENTRYEOF

RUN chmod +x /usr/local/bin/entrypoint.sh && \
    chown -R user:user /app/core /app/scripts

# ═══════════════════════════════════════════════════════════════════════════════
# 13. Finalization
# ═══════════════════════════════════════════════════════════════════════════════
WORKDIR /app
RUN touch /app/.env && chown user:user /app/.env

# Expose ALL ports for flexible HF Space URL mapping
EXPOSE ${APP_PORT} ${FRONTEND_PORT} ${BACKEND_PORT}

# FIX #3: Health check with 120s start-period (allows full initialization)
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \
    CMD curl -f http://localhost:${APP_PORT}/health 2>/dev/null || exit 1

# Use Entrypoint to start all services, then run the keep-alive server
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["/opt/venv/bin/python", "/app/core/boot.py"]