import sys
import json
import asyncio
import os

# Add directory to sys.path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app.services import locket, nextdns
from app.config import TOKEN_SETS_CONFIG, NEXTDNS_KEY

async def main():
    if len(sys.argv) < 2:
        print(json.dumps({"success": False, "error": "Missing username/UID argument"}))
        return

    target = sys.argv[1].strip()
    if "locket.cam/" in target:
        target = target.split("locket.cam/")[-1].split("?")[0]
    target = target.replace("@", "")

    # 1. Resolve UID
    uid, avatar = await locket.resolve_uid_with_avatar(target)
    if not uid:
        if len(target) == 28 and target.isalnum():
            uid = target
        else:
            print(json.dumps({"success": False, "error": f"Không tìm thấy tài khoản: {target}"}))
            return

    # 2. Check if already active
    status = await locket.check_status(uid)

    is_lookup = len(sys.argv) > 2 and sys.argv[2] == "--lookup"
    if is_lookup:
        is_active = (status and status.get("active", False)) if status else False
        result = {
            "success": True,
            "action": "lookup",
            "uid": uid,
            "username": target,
            "avatar": avatar,
            "is_gold": is_active,
            "expires": status.get("expires") if status else None
        }
        print(json.dumps(result))
        return
    
    logs = []
    def log_cb(msg):
        clean = msg.replace('\033[95m','').replace('\033[94m','').replace('\033[92m','').replace('\033[93m','').replace('\033[91m','').replace('\033[0m','').replace('\033[1m','')
        logs.append(clean)

    # 3. Inject Gold with Receipt Token
    token_config = TOKEN_SETS_CONFIG[0]
    success, msg = await locket.inject_gold(uid, token_config, log_cb)

    # 4. Generate Anti-Revoke NextDNS profile
    pid, link = await nextdns.create_profile(NEXTDNS_KEY, log_cb)
    mobileconfig_path = nextdns.generate_mobileconfig(pid, target) if pid else None

    # Verify final status
    final_status = await locket.check_status(uid)
    is_active = (final_status and final_status.get("active", False))

    result = {
        "success": success or is_active,
        "uid": uid,
        "username": target,
        "avatar": avatar,
        "is_gold": is_active,
        "expires": final_status.get("expires") if final_status else None,
        "message": msg,
        "dns_pid": pid,
        "dns_link": link,
        "mobileconfig_path": mobileconfig_path,
        "logs": logs
    }
    print(json.dumps(result))

if __name__ == "__main__":
    asyncio.run(main())
