Spaces:
Sleeping

File size: 26,090 Bytes
1ac29c1
 
 
 
 
 
8dfc6bd
bc545f4
5156c8e
d070f83
b659e34
 
af257db
7257f1f
1ac29c1
f04eafe
5f96f18
6a36ced
8838b65
a0194e3
8c5ec1a
 
 
9e06c96
93e8510
5b5ca3d
2c4f89c
ef60cb6
5156c8e
6f0d870
93195fb
9bc97e4
bc545f4
ee2faa1
 
c6f6672
aa2906c
 
9dd1c92
7821e42
d070f83
4f206b4
8120b14
a08e411
aa9d258
d108f5a
417f074
d77fda7
7b62c0c
 
fb2b5af
a83ff2b
 
 
 
 
 
 
 
 
 
c684bc5
 
0a906ff
c684bc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a906ff
c684bc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62908b1
 
 
 
0a906ff
c684bc5
 
 
 
 
 
 
 
 
 
5c575bd
 
 
 
 
 
 
 
 
 
 
c684bc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a906ff
 
 
 
 
 
 
 
 
 
 
 
 
c684bc5
 
 
 
 
 
0a906ff
c684bc5
 
 
 
 
0a906ff
 
 
 
c684bc5
 
 
0a906ff
 
c684bc5
5c575bd
c684bc5
 
5c575bd
 
 
 
 
 
 
c684bc5
5c575bd
 
 
 
c684bc5
5c575bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62908b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c575bd
0a906ff
 
 
 
 
 
 
 
 
 
 
 
62908b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a906ff
 
 
c684bc5
0a906ff
 
c684bc5
0a906ff
c684bc5
 
 
 
 
 
 
3100216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os


os.environ["HF_HUB_CACHE"] = "/tmp/hf_cache"
os.makedirs("/tmp/hf_cache", exist_ok=True)

from fastapi import FastAPI
from routes import dem_pyc, tong_doanh_thu_pyc, dem_pyc_hoan_thanh, doanh_thu_theo_thang, doanh_thu_dich_vu, tai_pdf, danh_sach_pdf, quy_trinh, danh_muc_thiet_bi  # hoặc import từ file dem_pyc nếu không có thư mục routes
from routes import ds_pyc_tat_ca, ds_pyc_hoan_thanh, doanh_thu_chi_tiet, pyc_chua_hoan_thanh, ty_le_dich_vu, doanh_thu_tong_hop, ds_pyc_cho_xu_ly, doanh_thu_tong, doanh_thu_noi_bo
from routes import cap_nhat_hoa_chat, quan_ly_hoa_chat, canh_bao_hoa_chat, hien_thi_hskh, cap_nhat_hskh, lay_thong_tin_pyc, upload_pyc, upload_kemtheo
from routes import banggia6, banggia2, banggia4, banggia3, danh_sach_thu_muc_khach_hang, banggia5
from routes.chatbot_routes import router as chatbot_router
app = FastAPI()


app.include_router(dem_pyc.router)
app.include_router(tong_doanh_thu_pyc.router)
app.include_router(dem_pyc_hoan_thanh.router)
app.include_router(doanh_thu_theo_thang.router)
app.include_router(doanh_thu_dich_vu.router)
app.include_router(ds_pyc_tat_ca.router)
app.include_router(ds_pyc_hoan_thanh.router)
app.include_router(doanh_thu_chi_tiet.router)
app.include_router(pyc_chua_hoan_thanh.router)
app.include_router(ty_le_dich_vu.router)
app.include_router(doanh_thu_tong_hop.router)
app.include_router(ds_pyc_cho_xu_ly.router)
app.include_router(doanh_thu_tong.router)
app.include_router(doanh_thu_noi_bo.router)
app.include_router(tai_pdf.router)
app.include_router(danh_sach_pdf.router)
app.include_router(quy_trinh.router)
app.include_router(danh_muc_thiet_bi.router)
app.include_router(cap_nhat_hoa_chat.router)
app.include_router(quan_ly_hoa_chat.router)
app.include_router(canh_bao_hoa_chat.router)
app.include_router(hien_thi_hskh.router)
app.include_router(cap_nhat_hskh.router)
app.include_router(lay_thong_tin_pyc.router)
app.include_router(upload_pyc.router)
app.include_router(upload_kemtheo.router)
app.include_router(banggia6.router)
app.include_router(banggia2.router)
app.include_router(banggia4.router)
app.include_router(banggia3.router)
app.include_router(danh_sach_thu_muc_khach_hang.router)
app.include_router(banggia5.router)
app.include_router(chatbot_router)
@app.get("/")
def root():
    return {"message": "✅ Backend is running"}
# ====== chatbot / rag / actions ======
from typing import List, Optional
from pydantic import BaseModel
from fastapi import APIRouter, Body
import re, datetime, httpx

from openai import OpenAI
from rag_indexer import build_index, search as rag_search
from actions import router as tabular_router
from intents import is_table_query, extract_keywords
# ================== CHATBOT – GPT-5 + RAG + ACTION ==================
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
MODEL_NAME     = os.environ.get("OPENAI_MODEL","gpt-5")
client = OpenAI(api_key=OPENAI_API_KEY)

# -------- ReIndex (quét dataset & lập chỉ mục) --------
router_rag = APIRouter()

@router_rag.post("/reindex")
def reindex():
    out = build_index()
    return {"status":"ok", **out}

# -------- Chat dựa trên dữ liệu nội bộ (RAG) ----------
class AskReq(BaseModel):
    question: str
    history: Optional[List[dict]] = []

def _llm_complete(prompt: str) -> str:
    rsp = client.chat.completions.create(
        model=MODEL_NAME, temperature=0.2,
        messages=[{"role":"system","content":
                   "Bạn là trợ lý nội bộ. Chỉ trả lời dựa trên NGỮ CẢNH nếu có; nếu thiếu thông tin thì nói rõ không đủ trong dữ liệu nội bộ."},
                  {"role":"user","content":prompt}]
    )
    return rsp.choices[0].message.content.strip()

@router_rag.post("/chat_rag")
def chat_rag(req: AskReq):
    hits = rag_search(req.question, top_k=6)
    ctx = "\n".join([f"- {h['repo_path']}: {h['preview']}" for h in hits]) or "(không tìm thấy ngữ cảnh phù hợp)"
    hist = "\n".join([f"[{m.get('role','user')}] {m.get('content','')}" for m in (req.history or [])][-6:])

    prompt = f"""
NGỮ CẢNH (trích từ dữ liệu nội bộ):
{ctx}

LỊCH SỬ:
{hist}

YÊU CẦU:
- Trả lời bằng tiếng Việt, dựa trên NGỮ CẢNH ở trên.
- Nếu NGỮ CẢNH không đủ hoặc không liên quan, nói rõ: "Mình chưa thấy đủ thông tin trong dữ liệu nội bộ."
- Cuối câu trả lời, liệt kê 'Nguồn' (các repo_path nổi bật).

CÂU HỎI: {req.question}
"""
    ans = _llm_complete(prompt)
    sources = list({h['repo_path'] for h in hits})[:5]
    return {"reply": ans, "sources": sources, "hits": hits}

app.include_router(router_rag)

# -------- Chat thường --------
router_chat = APIRouter()

class ChatReq(BaseModel):
    messages: List[dict]

@router_chat.post("/chat")
def chat(req: ChatReq):
    sys_prompt = {"role":"system","content":"Bạn là chatbot nội bộ, trả lời ngắn gọn, rõ ràng bằng tiếng Việt."}
    msgs = [sys_prompt] + (req.messages[-15:] if req.messages else [])
    rsp = client.chat.completions.create(model=MODEL_NAME, messages=msgs, temperature=0.2)
    return {"reply": rsp.choices[0].message.content}

app.include_router(router_chat)

# -------- Chat tự phân loại (ACTION / RAG / GENERAL) --------
router_smart = APIRouter()

class SmartReq(BaseModel):
    message: str
    history: Optional[List[dict]] = []

class SmartResp(BaseModel):
    intent: str
    reply: str
    sources: Optional[List[str]] = None

KEY_PYC_PENDING = [
    r"PYC\s*chưa\s*hoàn\s*thành", r"chưa\s*hoàn\s*thành",
    r"chờ\s*xử\s*lý", r"cho\s*xu\s*ly"   # <== thêm 2 regex này
]
KEY_REVENUE = [r"doanh\s*thu", r"tháng\s*\d{1,2}", r"\b\d{1,2}\/\d{4}\b"]

def _has(t, pats): return any(re.search(p, t, flags=re.I) for p in pats)

def _mon_year(t:str):
    t=t.lower()
    m=re.search(r"tháng\s*(\d{1,2})(?:[\/\-](\d{4}))?",t)
    if m: return int(m.group(1)), int(m.group(2)) if m.group(2) else datetime.date.today().year
    m2=re.search(r"\b(\d{1,2})\/(\d{4})\b",t)
    if m2: return int(m2.group(1)), int(m2.group(2))
    return None,None
# thêm ngay dưới _mon_year(t: str)
def _mon_year_from_history(history):
    if not history:
        return (None, None)
    # duyệt ngược để lấy câu gần nhất có "tháng"
    for msg in reversed(history):
        t = msg.get("content", "") or ""
        m, y = _mon_year(t)
        if m:
            return (m, y)
    return (None, None)

async def _GET(path, params):
    for base in ["","http://127.0.0.1:7860","http://127.0.0.1:8000"]:
        url = f"{base}{path}" if base else path
        try:
            async with httpx.AsyncClient(timeout=60) as c:
                r=await c.get(url, params=params)
                if r.status_code==200: return r.json()
        except: pass
    return {"error": f"GET fail {path}"}

async def _POST(path, payload):
    for base in ["","http://127.0.0.1:7860","http://127.0.0.1:8000"]:
        url = f"{base}{path}" if base else path
        try:
            async with httpx.AsyncClient(timeout=60) as c:
                r=await c.post(url, json=payload)
                if r.status_code==200: return r.json()
        except: pass
    return {"error": f"POST fail {path}"}

def _format_rows(rows: List[dict], max_cols: int = 6) -> str:
    if not rows: return "Không tìm thấy dòng phù hợp."
    # mỗi row {"source": "...", "row": {...}}
    lines = []
    for i, item in enumerate(rows, 1):
        src = item.get("source","")
        row = item.get("row", {})
        # lấy vài cột đầu
        cols = list(row.keys())[:max_cols]
        parts = [f"{k}: {row[k]}" for k in cols]
        lines.append(f"{i}. ({src}) " + " | ".join(parts))
    return "\n".join(lines)

@router_smart.post("/chat_smart", response_model=SmartResp)
async def chat_smart(req: SmartReq = Body(...)):
    text = (req.message or "").strip()
    if not text:
        return SmartResp(intent="general", reply="Bạn hãy nhập câu hỏi hoặc yêu cầu nhé.")

    # ACTION: PYC chưa hoàn thành
    if _has(text, KEY_PYC_PENDING):
        data = await _GET("/pyc_chua_hoan_thanh", {})
        if "error" in data: return SmartResp(intent="action.list_pyc_pending", reply="Không lấy được danh sách.")
        rows = data if isinstance(data,list) else data.get("rows") or data.get("data") or []
        if not rows: return SmartResp(intent="action.list_pyc_pending", reply="Hiện không có PYC chưa hoàn thành.")
        top = rows[:10]
        if isinstance(top[0], dict):
            lines = []
            for r in top:
                so = r.get("SỐ PYC") or r.get("so_pyc") or r.get("pyc") or ""
                kh = r.get("Tên khách hàng") or r.get("ten_khach_hang") or r.get("khach_hang") or ""
                lines.append(f"- {so} | {kh}")
            return SmartResp(intent="action.list_pyc_pending", reply="\n".join(lines))
        return SmartResp(intent="action.list_pyc_pending", reply="\n".join([f"- {r}" for r in top]))

    # ACTION: Doanh thu tháng (trả đúng 1 tháng)
    if _has(text, KEY_REVENUE):
        mon, yr = _mon_year(text)
        if not mon:
            # thử lấy từ lịch sử hội thoại
            mon, yr = _mon_year_from_history(req.history)
        if not mon:
            return SmartResp(intent="action.revenue_month.ask",
                             reply="Bạn muốn xem doanh thu **tháng nào**? (vd: tháng 7/2025)")
    
        data = await _GET("/doanh_thu_theo_thang", {"month": mon, "year": yr})
        if "error" in data:
            return SmartResp(intent="action.revenue_month", reply="Không lấy được doanh thu.")
    
        # 3 trường hợp: API trả 'tong_doanh_thu' / 'total' / mảng 'doanh_thu' theo 12 tháng
        total = data.get("tong_doanh_thu") or data.get("total") or data.get("sum")
        if total is None and isinstance(data.get("doanh_thu"), list):
            arr = data["doanh_thu"]
            idx = mon - 1
            if 0 <= idx < len(arr):
                total = arr[idx]
    
        if total is None:
            return SmartResp(intent="action.revenue_month", reply=f"Kết quả: {data}")
    
        year_show = yr or datetime.date.today().year
        try:
            total_fmt = f"{int(total):,}"
        except:
            total_fmt = str(total)
        return SmartResp(intent="action.revenue_month",
                         reply=f"Doanh thu tháng {str(mon).zfill(2)}/{year_show}: **{total_fmt} VND**")
    # === GIÁ / BẢNG GIÁ (bắt cả không dấu) ===
    txt_no = re.sub(r"[^\w\s]", " ", text.lower())
    txt_no = (txt_no.replace("á","a").replace("à","a").replace("ã","a").replace("ả","a").replace("ạ","a")
                      .replace("â","a").replace("ă","a").replace("đ","d")
                      .replace("ó","o").replace("ò","o").replace("ô","o").replace("ơ","o").replace("õ","o").replace("ọ","o")
                      .replace("é","e").replace("è","e").replace("ê","e").replace("ẽ","e").replace("ẹ","e")
                      .replace("í","i").replace("ì","i").replace("ĩ","i").replace("ị","i")
                      .replace("ú","u").replace("ù","u").replace("ũ","u").replace("ụ","u").replace("ư","u"))
    
    if re.search(r"\b(bao gia|bang gia|gia)\b", txt_no):
        nhom = None
        if "hoa ly" in txt_no or "hóa lý" in text.lower():
            nhom = "hóa lý"
        elif "dien" in txt_no or "điện" in text.lower():
            nhom = "điện"
        elif "co do dai" in txt_no or "cơ độ dài" in text.lower() or "ap suat" in txt_no or "áp suất" in text.lower():
            nhom = "cơ/áp suất"
        elif "nhiet" in txt_no or "y te" in txt_no or "nhiệt" in text.lower() or "y tế" in text.lower():
            nhom = "nhiệt/y tế"
        elif "dung tich" in txt_no or "luu luong" in txt_no:
            nhom = "dung tích/lưu lượng"
        elif "khoi luong" in txt_no or "khối lượng" in text.lower():
            nhom = "khối lượng"
    
        if nhom:
            return SmartResp(intent="action.open_price_table",
                             reply=f"Mở **Bảng giá tham khảo** ({nhom}). Vào mục *Bảng giá tham khảo* ở menu.")
        else:
            return SmartResp(intent="action.open_price_table",
                             reply="Mở **Bảng giá tham khảo**. Vào mục *Bảng giá tham khảo* ở menu để chọn nhóm.")
    
    # === PHIẾU YÊU CẦU ===
    if "phiếu yêu cầu" in text.lower() or "phieu yeu cau" in txt_no or "pyc" in txt_no:
        return SmartResp(intent="action.pyc",
                         reply="Bạn muốn xem **PYC chờ xử lý**, **đã hoàn thành** hay **tất cả**? Vào menu *Phiếu yêu cầu* để chọn.")
    # ACTION: PYC chờ xử lý / chưa hoàn thành
    if _has(text, KEY_PYC_PENDING) or text.strip().lower() in {"pyc chờ xử lý","pyc cho xu ly"}:
        # ưu tiên API liệt kê PYC chờ xử lý nếu có
        data = await _GET("/ds_pyc_cho_xu_ly", {})  # bạn có route này
        if "error" in data or not data:
            # fallback sang API PYC chưa hoàn thành
            data = await _GET("/pyc_chua_hoan_thanh", {})
        rows = data if isinstance(data, list) else data.get("rows") or data.get("data") or []
        if not rows:
            return SmartResp(intent="action.list_pyc_pending", reply="Hiện không có PYC chờ xử lý.")
        # render gọn top 10
        out = []
        for r in rows[:10]:
            if isinstance(r, dict):
                so = r.get("SỐ PYC") or r.get("so_pyc") or r.get("pyc") or ""
                kh = r.get("Tên khách hàng") or r.get("ten_khach_hang") or r.get("khach_hang") or ""
                out.append(f"- {so} | {kh}")
            else:
                out.append(f"- {r}")
        return SmartResp(intent="action.list_pyc_pending", reply="\n".join(out))
            
        # ACTION: Câu hỏi dạng bảng (bảng giá/thiết bị/khách hàng/hóa chất…)
    if is_table_query(text):
        # rút từ khóa gọn để search
        kws = extract_keywords(text)
        q = " ".join(kws) if kws else text
        data = await _GET("/tabular_search", {"q": q, "limit": 10})
        rows = data.get("data", [])
        if rows:
            return SmartResp(intent="action.tabular_search", reply=_format_rows(rows))
        # fallback: RAG
        data_rag = await _POST("/chat_rag", {"question": text, "history": req.history or []})
        if data_rag.get("reply"):
            return SmartResp(intent="rag.query", reply=data_rag["reply"], sources=data_rag.get("sources"))
    # === TÀI LIỆU / PDF ===
    if re.search(r"(tài\s*liệu|tai\s*lieu|pdf|quy\s*trình|quy\s*trinh|document)", text, flags=re.I):
        # nếu có API danh sách PDF thì liệt kê nhanh top 8
        data = await _GET("/danh_sach_pdf", {})
        items = []
        if isinstance(data, dict):
            arr = data.get("files") or data.get("data") or []
        else:
            arr = data or []
        for p in arr[:8]:
            name = p if isinstance(p, str) else (p.get("name") or p.get("path") or "")
            if name:
                items.append(f"• {name}")
        reply = "Mở **Tài liệu (PDF)**. " + ("Dưới đây là một số tệp:\n" + "\n".join(items) if items else "")
        return SmartResp(intent="action.docs", reply=reply)

    # RAG: nếu nhắc tới tài liệu/quy trình/báo giá…
    if re.search(r"(quy\s*trình|tài\s*liệu|báo\s*giá|PYC|hợp\s*đồng)", text, flags=re.I):
        data = await _POST("/chat_rag", {"question": text, "history": req.history or []})
        if data.get("reply"):
            return SmartResp(intent="rag.query", reply=data["reply"], sources=data.get("sources"))

    # GENERAL
    msgs = (req.history or []) + [{"role":"user","content":text}]
    out = await _POST("/chat", {"messages": msgs})
    reply = out.get("reply") or "Xin lỗi, mình chưa trả lời được."
    return SmartResp(intent="general", reply=reply)

app.include_router(router_smart)
# ================== HẾT PHẦN CHATBOT ==================
# ================== PYC INCREMENTAL (tích hợp trực tiếp) ==================
# Đọc Excel trong dataset Hugging Face: doluong6/Quatest1/Phieu_yeu_cau/
# Chỉ xử lý file mới kể từ lần trước, gộp vào cache (~ /tmp/hf_cache/pyc_cache.json)

import os, re, json
from typing import Dict, List, Optional, Tuple
from fastapi import APIRouter, Query
from pydantic import BaseModel
from huggingface_hub import list_repo_files, hf_hub_download
from openpyxl import load_workbook

# --------- Cấu hình chính ---------
REPO_ID   = os.environ.get("REPO_ID", "doluong6/Quatest1")
HF_TOKEN  = os.environ.get("HF_TOKEN")            # để trống nếu dataset public
HF_CACHE  = os.environ.get("HF_HUB_CACHE", "/tmp/hf_cache")
os.makedirs(HF_CACHE, exist_ok=True)

PYC_SCOPE = os.environ.get("PYC_FOLDER", "Phieu_yeu_cau/")
if not PYC_SCOPE.endswith("/"): PYC_SCOPE += "/"

# Cột theo template PYC
COL_QTY   = "BM"  # số lượng
COL_PRICE = "BP"  # đơn giá
COL_KD    = "AV"  # "P" => KĐ
COL_HC    = "AY"  # "P" => HC
COL_DTN   = "BB"  # "P" => ĐTN

COL_DAY   = "BM3"  # ngày (số)
COL_MONTH = "BS3"  # tháng (chuỗi số 1..12)
COL_CUST  = "I8"   # tên khách hàng

START_ROW = 24     # dòng bắt đầu duyệt dịch vụ

CACHE_PATH = os.path.join(HF_CACHE, "pyc_cache.json")

router_pyc_inc = APIRouter(prefix="/pyc_incremental", tags=["PYC-incremental"])

# --------- Tiện ích ---------
def _safe_float(x) -> float:
    try:
        return float(x)
    except Exception:
        return 0.0

def _to_month_int(x) -> Optional[int]:
    if x is None: return None
    s = str(x).strip()
    if not s.isdigit(): return None
    m = int(s)
    return m if 1 <= m <= 12 else None

def _period_of(day: Optional[int]) -> Optional[str]:
    if day is None: return None
    return "1_15" if day <= 15 else "16_31"

def _iter_services(ws):
    r = START_ROW
    while True:
        qty = ws[f"{COL_QTY}{r}"].value
        if qty is None: break
        price = ws[f"{COL_PRICE}{r}"].value
        kd = str(ws[f"{COL_KD}{r}"].value or "").strip().upper() == "P"
        hc = str(ws[f"{COL_HC}{r}"].value or "").strip().upper() == "P"
        dtn= str(ws[f"{COL_DTN}{r}"].value or "").strip().upper() == "P"
        yield _safe_float(qty), _safe_float(price), kd, hc, dtn
        r += 1

def _extract_number(basename: str) -> Optional[int]:
    # lấy số trong tên file: PYC_0158.xlsx, 0158.xlsx, pyc-158.xlsx, ...
    m = re.search(r"(\d{3,5})", basename)
    return int(m.group(1)) if m else None

def _download(repo_path: str) -> str:
    return hf_hub_download(
        REPO_ID, repo_path, repo_type="dataset",
        token=HF_TOKEN, cache_dir=HF_CACHE
    )

# --------- Cache ---------
def _load_cache() -> Dict:
    if os.path.exists(CACHE_PATH):
        try:
            with open(CACHE_PATH, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception:
            pass
    return {
        "version": 1,
        "repo_id": REPO_ID,
        "scope": PYC_SCOPE,
        # files: { repo_path: { "num": 158, "month":7, "day":12, "customer":"...",
        #                       "totals":{"KĐ":..,"HC":..,"ĐTN":..},
        #                       "revenue":{"KĐ":..,"HC":..,"ĐTN":..} } }
        "files": {}
    }

def _save_cache(cache: Dict):
    tmp = CACHE_PATH + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(cache, f, ensure_ascii=False)
    os.replace(tmp, CACHE_PATH)

def _list_repo_files() -> List[str]:
    files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
    return [f for f in files
            if f.startswith(PYC_SCOPE)
            and f.lower().endswith(".xlsx")
            and not os.path.basename(f).startswith("~$")]

def _process_file(local_path: str):
    """
    Trả (totals, revenue, month, day, customer)
    """
    wb = load_workbook(local_path, data_only=True)
    ws = wb.active
    day_val   = ws[COL_DAY].value
    month_val = ws[COL_MONTH].value
    cust_val  = str(ws[COL_CUST].value or "").strip()
    day   = int(day_val) if isinstance(day_val, (int, float)) else None
    month = _to_month_int(month_val)

    totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
    revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}

    for sl, gia, kd, hc, dtn in _iter_services(ws):
        if kd:
            totals["KĐ"] += sl
            revenue["KĐ"] += sl * gia
        if hc:
            totals["HC"] += sl
            revenue["HC"] += sl * gia
        if dtn:
            totals["ĐTN"] += sl
            revenue["ĐTN"] += sl * gia

    for k in totals: totals[k] = round(totals[k], 2)
    for k in revenue: revenue[k] = round(revenue[k], 0)
    return totals, revenue, month, day, cust_val

def _refresh_cache(cache: Dict) -> Dict:
    """
    Quét repo, chỉ xử lý file MỚI (chưa có trong cache). Sắp theo số tăng dần.
    """
    existing = set(cache["files"].keys())
    all_files = _list_repo_files()
    new_files = [rp for rp in all_files if rp not in existing]

    def _sort_key(rp: str):
        n = _extract_number(os.path.basename(rp)) or 10**9
        return (n, rp)
    new_files.sort(key=_sort_key)

    added = 0
    for rp in new_files:
        try:
            lp = _download(rp)
            totals, revenue, month, day, cust = _process_file(lp)
            num = _extract_number(os.path.basename(rp))
            cache["files"][rp] = {
                "num": num, "month": month, "day": day,
                "customer": cust, "totals": totals, "revenue": revenue
            }
            added += 1
        except Exception as e:
            cache["files"][rp] = {"error": str(e)}
    if added:
        _save_cache(cache)
    return {"added": added, "known": len(cache["files"])}

# --------- Schemas ---------
class IncStateResp(BaseModel):
    repo_id: str
    scope: str
    known: int
    newest_num: Optional[int] = None
    added: int

class IncStatsResp(BaseModel):
    month: Optional[int] = None
    period: Optional[str] = None    # '1_15' | '16_31' | None
    totals: Dict[str, float]
    revenue: Dict[str, float]
    customers: List[str]
    files: List[str]

# --------- Endpoints ---------
@router_pyc_inc.post("/refresh", response_model=IncStateResp)
def pyc_inc_refresh():
    """
    Incremental refresh: chỉ xử lý file mới kể từ lần trước.
    Frontend nên gọi endpoint này khi mở mục để cập nhật nhanh.
    """
    cache = _load_cache()
    out = _refresh_cache(cache)
    nums = [v.get("num") for v in cache["files"].values() if isinstance(v, dict) and v.get("num") is not None]
    newest = max(nums) if nums else None
    return {"repo_id": cache["repo_id"], "scope": cache["scope"],
            "known": out["known"], "added": out["added"], "newest_num": newest}

@router_pyc_inc.get("/stats", response_model=IncStatsResp)
def pyc_inc_stats(
    month: Optional[int] = Query(default=None, ge=1, le=12),
    period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"),
    refresh_first: bool = Query(default=True)
):
    """
    Lấy thống kê nhanh từ cache. Nếu refresh_first=true → xử lý file mới trước khi trả kết quả.
    """
    cache = _load_cache()
    if refresh_first:
        _refresh_cache(cache)

    totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
    revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
    customers = set()
    used_files = []

    def _ok(meta) -> bool:
        return isinstance(meta, dict) and "error" not in meta

    for rp, meta in cache["files"].items():
        if not _ok(meta): continue
        if month is not None and meta.get("month") != month: continue
        if period is not None and _period_of(meta.get("day")) != period: continue

        t = meta.get("totals", {}); r = meta.get("revenue", {})
        for k in totals: totals[k] += float(t.get(k, 0))
        for k in revenue: revenue[k] += float(r.get(k, 0))
        if meta.get("customer"): customers.add(meta["customer"])
        used_files.append(rp)

    for k in totals: totals[k] = round(totals[k], 2)
    for k in revenue: revenue[k] = round(revenue[k], 0)
    return {
        "month": month, "period": period,
        "totals": totals, "revenue": revenue,
        "customers": sorted(customers), "files": used_files
    }

@router_pyc_inc.get("/list")
def pyc_inc_list(
    month: Optional[int] = Query(default=None, ge=1, le=12),
    period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"),
    limit: int = Query(default=200, ge=1, le=1000),
    refresh_first: bool = Query(default=False)
):
    """
    Danh sách file đã biết (từ cache), có thể lọc theo month/period.
    """
    cache = _load_cache()
    if refresh_first:
        _refresh_cache(cache)
    out = []
    for rp, meta in cache["files"].items():
        if not isinstance(meta, dict) or "error" in meta: 
            continue
        if month is not None and meta.get("month") != month: continue
        if period is not None and _period_of(meta.get("day")) != period: continue
        out.append({
            "repo_path": rp, "num": meta.get("num"),
            "month": meta.get("month"), "day": meta.get("day"),
            "customer": meta.get("customer"),
            "totals": meta.get("totals"), "revenue": meta.get("revenue")
        })
    out.sort(key=lambda x: (x.get("num") if x.get("num") is not None else 10**9, x["repo_path"]))
    return {"count": len(out), "items": out[:limit]}

@router_pyc_inc.post("/reset")
def pyc_inc_reset():
    """
    XÓA cache → lần sau /refresh sẽ build lại từ đầu.
    """
    if os.path.exists(CACHE_PATH):
        os.remove(CACHE_PATH)
    return {"status": "ok", "msg": "Cache cleared"}

# Đăng ký router mới
app.include_router(router_pyc_inc)
# ================== HẾT PHẦN PYC INCREMENTAL ==================