import argparse
from time import sleep
from tqdm import tqdm
import os
import browsercookie
import pandas as pd
import requests
import subprocess
import glob


def search_telco(mobile_no, session_id):
    url = "https://ccib.cyberpolice.go.th/web/dataset/call_kw/tj_ccib_5c.telco_request/web_search_read"
    cookies = {"cids": "1", "frontend_lang": "th_TH", "tz": "Asia/Bangkok", "session_id": session_id}
    payload = {
        "id": 73,
        "jsonrpc": "2.0",
        "method": "call",
        "params": {
            "model": "tj_ccib_5c.telco_request",
            "method": "web_search_read",
            "args": [],
            "kwargs": {
                "domain": [["mobile_no", "ilike", mobile_no]],
                # "fields": ["mobile_no", "state"],
            },
        },
    }

    response = requests.post(url, cookies=cookies, json=payload)
    if response.ok:
        return response.json()


def get_registra_name(input_file, column_name):
    result = ""
    try:
        df = pd.read_excel(input_file).head(10)
        if column_name not in df.columns:
            return result

        name = df[column_name].dropna().astype(str).unique()
        print(name)
    except Exception as e:
        print(e)
    finally:
        return result


def get_mobile_number_and_id(input_file, telephone_column, name_column, session_id):
    results = []
    try:
        df = pd.read_excel(input_file)
        if telephone_column not in df.columns:
            return []

        for _, row in tqdm(df.iterrows(), total=len(df), desc="Mobile Extracts"):
            num = str(row[telephone_column]).strip()
            if not num or num.lower() == "nan":
                continue

            registra_name = "export"
            if name_column != "export":
                registra_name = str(row[name_column]).strip() if not pd.isna(row[name_column]) else ""

            data = search_telco(num.zfill(10), session_id)

            data = data.get("result", {"length": 0, "records": []})
            if len(data["records"]) > 0:
                received_result = [record for record in data["records"] if record.get("nbtc_status_code", 500) == 200]
                results.append(
                    {"registra_name": registra_name, "mobile_no": num, "id": received_result[0].get("id", "") if received_result else "", "data": received_result[0] if received_result else {}}
                )
    except Exception as e:
        print(e)
    finally:
        return results


def download_with_curl(output_path, mobile_id, session_id, csrf_token):
    os.makedirs(os.path.dirname(output_path), exist_ok=True)

    curl_cmd = f"""
curl -s 'https://ccib.cyberpolice.go.th/report/download' \
  -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryZ3ZnRlc294uzHsZx' \
  -b 'cids=1; frontend_lang=th_TH; tz=Asia/Bangkok; session_id={session_id}' \
  -H 'Origin: https://ccib.cyberpolice.go.th' \
  -H 'Referer: https://ccib.cyberpolice.go.th/web' \
  --data-raw $'------WebKitFormBoundaryZ3ZnRlc294uzHsZx\\r\\nContent-Disposition: form-data; name="data"\\r\\n\\r\\n["/report/pdf/tj_ccib_smartdoc.number_audit_form/{mobile_id}","qweb-pdf"]\\r\\n------WebKitFormBoundaryZ3ZnRlc294uzHsZx\\r\\nContent-Disposition: form-data; name="context"\\r\\n\\r\\n{{"lang":"en_US","tz":"Asia/Bangkok","uid":4539,"allowed_company_ids":[1]}}\\r\\n------WebKitFormBoundaryZ3ZnRlc294uzHsZx\\r\\nContent-Disposition: form-data; name="token"\\r\\n\\r\\ndummy-because-api-expects-one\\r\\n------WebKitFormBoundaryZ3ZnRlc294uzHsZx\\r\\nContent-Disposition: form-data; name="csrf_token"\\r\\n\\r\\n{csrf_token}\\r\\n------WebKitFormBoundaryZ3ZnRlc294uzHsZx--\\r\\n' \
  --output "{output_path} >"
"""

    subprocess.run(curl_cmd, shell=True, check=True)


def check_session():
    url = "https://ccib.cyberpolice.go.th/web"
    cli_cookies = browsercookie.chrome()
    response = requests.get(url, cookies=cli_cookies)

    cookie_header = response.headers.get("Set-Cookie", "")
    session_id = cookie_header.split("session_id=")[-1].split(";")[0]
    return session_id


import glob


def main():
    session_id = check_session()
    if not session_id:
        print("กรุณาเข้าสู่ระบบที่ https://ccib.cyberpolice.go.th/web/session/login")
        return

    parser = argparse.ArgumentParser(description="โหลด PDF จาก 5C")
    parser.add_argument("-i", "--input_path", help="Folder ที่เก็บไฟล์ Excel ต้นฉบับ")
    parser.add_argument("-n", "--name_column", default="ผู้รับจดทะเบียน", help="ชื่อคอลัมน์ที่มีหมายเลขโทรศัพท์")
    parser.add_argument("-c", "--telephone_column", default="โทรฯ คนร้าย", help="ชื่อคอลัมน์ที่มีหมายเลขโทรศัพท์")
    parser.add_argument("-t", "--csrf_token", required=True, help="csrf_token ดูได้จากการกด Download ไฟล์ pdf")
    args = parser.parse_args()

    input_path = args.input_path
    name_column = args.name_column
    telephone_column = args.telephone_column
    csrf_token = args.csrf_token

    excel_files = []
    if input_path and os.path.exists(input_path):
        excel_files = glob.glob(os.path.join(input_path, "*.xlsx")) + glob.glob(os.path.join(input_path, "*.xls"))
    else:
        excel_files = glob.glob("*.xlsx") + glob.glob("*.xls")

    if not excel_files:
        print("ไม่พบไฟล์ Excel ในโฟลเดอร์ปัจจุบัน")
        return
    for i, input_file in enumerate(excel_files):
        mobile_list = get_mobile_number_and_id(input_file, telephone_column, name_column, session_id)
    for item in tqdm(mobile_list, total=len(mobile_list), desc="PDF Downloading"):
        if item["id"] and item["registra_name"]:
            download_with_curl(f"{item['registra_name']}/0{item['mobile_no']}.pdf", item["id"], session_id, csrf_token)


if __name__ == "__main__":
    main()
