# transsion.py
# چک گارانتی Transsion (TECNO / Infinix / itel) با API پایدار بدون sign
# نسخه نهایی - دقیقاً طبق فرمت درخواستی شما (بدون تکرار footer و بدون پیام اضافی IMEI)
# تاریخ: 08 مارس 2026
# اصلاح: حذف فایل carlcare_requests.log بعد از پردازش کامل هر درخواست

import requests
import urllib3
import json
import os
from datetime import datetime

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

LOG_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_FILE = os.path.join(LOG_DIR, "carlcare_requests.log")

def log_request(tag, imei, url, headers=None, response_text=None, exception=None):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{timestamp}] [{tag}] IMEI={imei} | URL={url}\n"
    
    if headers:
        line += f"HEADERS: {json.dumps(headers, indent=2, ensure_ascii=False)}\n"
    if response_text:
        line += f"RESPONSE: {response_text[:2000]}{' ... (truncated)' if len(response_text) > 2000 else ''}\n"
    if exception:
        line += f"EXCEPTION: {str(exception)}\n"
    line += "-" * 100 + "\n"
    
    try:
        with open(LOG_FILE, "a", encoding="utf-8") as f:
            f.write(line)
    except:
        pass

COMMON_HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "en-US,en;q=0.9",
    "Origin": "https://www.carlcare.com",
    "Referer": "https://www.carlcare.com/",
    "Sec-Ch-Ua": '"Not.A/Brand";v="99", "Chromium";v="136"',
    "Sec-Ch-Ua-Mobile": "?0",
    "Sec-Ch-Ua-Platform": '"Windows"',
    "Sec-Fetch-Site": "same-site",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Connection": "keep-alive"
}

def format_date(date_str):
    if not date_str or date_str == "N/A":
        return "N/A"
    try:
        for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d", "%d-%m-%Y"]:
            try:
                dt = datetime.strptime(date_str, fmt)
                return dt.strftime("%B %d, %Y")
            except ValueError:
                continue
        return date_str
    except:
        return date_str

def build_tree_section(title, items):
    if not items:
        return ""
    out = f"<b>📂 {title}</b>\n"
    for i, line in enumerate(items):
        char = " └ " if i == len(items) - 1 else " ├ "
        out += f"{char}{line}\n"
    return out + "\n"

def process(imei):
    imei = str(imei).strip()
    if not imei.isdigit() or len(imei) < 14:
        # حتی در IMEI نامعتبر هم فایل لاگ را حذف می‌کنیم (اگر وجود داشته باشد)
        if os.path.exists(LOG_FILE):
            try:
                os.remove(LOG_FILE)
            except:
                pass
        return {"text": "❌ IMEI نامعتبر است (باید عدد و حداقل ۱۴ رقم باشد)"}

    # پاک کردن فایل لاگ قدیمی در ابتدای هر درخواست جدید
    if os.path.exists(LOG_FILE):
        try:
            os.remove(LOG_FILE)
        except:
            pass

    log_request("START", imei, "")

    policy_url = f"https://service.carlcare.com/CarlcareClient/electronic-card/imei-policy?imei={imei}"
    
    try:
        r = requests.get(
            policy_url,
            headers=COMMON_HEADERS,
            verify=False,
            timeout=12
        )
        log_request("POLICY", imei, policy_url, COMMON_HEADERS, r.text)
        
        if r.ok:
            d = r.json()
            if d.get("code") == 200:
                data = d.get("data", {})
                policies = data.get("valid", []) + data.get("invalid", [])
                
                brand = "Unknown"
                model = "Unknown"
                brand_category = "Unknown"
                channel_code = "Unknown"
                active_time = "N/A"
                warranty_duration = "N/A"
                grouped_policies = {}

                for p in policies:
                    p_type = p.get("profitsTypeName", "Unknown")
                    
                    if p.get("brandCategoryName"):
                        brand_category = p.get("brandCategoryName")
                    if p.get("productModelCode"):
                        model = p.get("productModelCode")
                    if p.get("channelCode"):
                        channel_code = p.get("channelCode")
                    
                    grouped_policies[p_type] = {
                        "status": "Valid ✅" if p.get("status") == "valid" else "Expired ❌",
                        "start": p.get("periodOfValid") or p.get("startDate"),
                        "end": p.get("expiryDate") or p.get("endDate"),
                        "duration": p.get("warrantyName") or "N/A",
                        "service_times": p.get("serviceTimes", 0),
                        "is_invalid": "Yes" if p.get("isInvalid") == 1 else "No"
                    }
                    
                    if "Finished Goods Warranty" in p_type or "FGW" in p_type:
                        active_time = p.get("periodOfValid") or p.get("startDate") or active_time
                        warranty_duration = p.get("expiryDate") or p.get("endDate") or warranty_duration
                
                bc_lower = brand_category.lower()
                if "itel" in bc_lower:
                    brand = "itel"
                elif "infinix" in bc_lower:
                    brand = "Infinix"
                elif "tecno" in bc_lower:
                    brand = "TECNO"

                # خروجی دقیقاً طبق نمونه‌ای که خواستی (بدون تکرار footer و بدون پیام اضافی)
                final_output = "✅ <b>Verification Successful</b>\n\n"

                brand_items = [
                    f"🏭 <b>Manufacturer</b>: <code>Transsion Holdings</code>",
                    f"🏷 <b>Category</b>: <code>{brand_category}</code>",
                    f"🅱️ <b>Brand</b>: <code>{brand}</code>"
                ]
                final_output += build_tree_section("Brand Information", brand_items)

                device_items = [
                    f"🛒 <b>Channel Code</b>: <code>{channel_code}</code>",
                    f"📲 <b>Model</b>: <code>{model}</code>"
                ]
                final_output += build_tree_section("Device Info", device_items)

                fgw = grouped_policies.get("Finished Goods Warranty") or grouped_policies.get("FGW")
                war_items = [
                    f"📅 <b>Active Time</b>: <code>{format_date(fgw['start'] if fgw else active_time)}</code>",
                    f"📅 <b>Valid To</b>: <code>{format_date(fgw['end'] if fgw else warranty_duration)}</code>",
                    f"📅 <b>Date Now</b>: <code>{datetime.now().strftime('%B %d, %Y')}</code>",
                    f"🛠 <b>Duration</b>: <code>{fgw['duration'] if fgw else 'N/A'}</code>",
                    f"⚙️ <b>Service Times</b>: <code>{fgw['service_times'] if fgw else 0}</code>",
                    f"🚫 <b>Is Invalid</b>: <code>{fgw['is_invalid'] if fgw else 'No'}</code>",
                    f"📆 <b>Status</b>: <code>{fgw['status'] if fgw else 'N/A'}</code>"
                ]
                final_output += build_tree_section("Warranty Info", war_items)

                dap = grouped_policies.get("DAP")
                if dap:
                    dap_items = [
                        f"📅 <b>Active Time</b>: <code>{format_date(dap['start'])}</code>",
                        f"📅 <b>Valid To</b>: <code>{format_date(dap['end'])}</code>",
                        f"📅 <b>Date Now</b>: <code>{datetime.now().strftime('%B %d, %Y')}</code>",
                        f"🛠 <b>Duration</b>: <code>{dap['duration']}</code>",
                        f"⚙️ <b>Service Times</b>: <code>{dap['service_times']}</code>",
                        f"🚫 <b>Is Invalid</b>: <code>{dap['is_invalid']}</code>",
                        f"📆 <b>Status</b>: <code>{dap['status']}</code>"
                    ]
                    final_output += build_tree_section("DAP (Dead on Arrival Policy) Info", dap_items)

                # بخش More Info – فقط IMEI 1 (ورودی)
                more_items = [
                    f"🔢 <b>IMEI 1</b>: <code>{imei}</code>"
                ]
                final_output += build_tree_section("More Info", more_items)

                # footer فقط یک بار
                final_output += "\nTo check another device, just send the new code.\nCheck By: @GlobalDeviceCheckerBot"

                log_request("FINISH", imei, policy_url, COMMON_HEADERS, "Processed using /imei-policy")

                # حذف فایل لاگ بعد از پردازش موفق
                if os.path.exists(LOG_FILE):
                    try:
                        os.remove(LOG_FILE)
                    except:
                        pass

                return {"text": final_output, "raw": d}
            else:
                # در صورت خطای API هم لاگ را حذف می‌کنیم
                if os.path.exists(LOG_FILE):
                    try:
                        os.remove(LOG_FILE)
                    except:
                        pass
                return {"text": f"❌ وضعیت نامعتبر: کد {d.get('code')}\nپیام: {d.get('message', 'No message')}"}
        else:
            if os.path.exists(LOG_FILE):
                try:
                    os.remove(LOG_FILE)
                except:
                    pass
            return {"text": f"❌ خطای سرور: {r.status_code}\n{r.text[:500]}"}

    except Exception as e:
        log_request("POLICY", imei, policy_url, COMMON_HEADERS, exception=e)
        
        # حذف لاگ حتی در حالت exception
        if os.path.exists(LOG_FILE):
            try:
                os.remove(LOG_FILE)
            except:
                pass
                
        return {"text": f"❌ خطا در ارتباط با سرور:\n{str(e)}"}