#!/usr/bin/env python3
_N='os_version'
_M='virtual_env_path'
_L='is_virtual_env'
_K='executable'
_J='version'
_I='email'
_H='\n'
_G='python'
_F='mac_address'
_E='hardware_uuid'
_D='device_id'
_C=True
_B='unknown'
_A=None
import os,sys,json,uuid,socket,platform,argparse,subprocess,hashlib
from pathlib import Path
from datetime import datetime
try:import requests
except ImportError:requests=_A
def get_hardware_uuid()->str:
	try:
		if platform.system()=='Darwin':
			A=subprocess.run(['system_profiler','SPHardwareDataType'],capture_output=_C,text=_C,timeout=5)
			for B in A.stdout.split(_H):
				if'UUID'in B:return B.split()[-1]
		elif platform.system()=='Linux':
			try:
				with open('/etc/machine-id','r')as C:return C.read().strip()
			except FileNotFoundError:pass
		elif platform.system()=='Windows':
			try:A=subprocess.run(['wmic','os','get','serialnumber'],capture_output=_C,text=_C,timeout=5);return A.stdout.strip().split(_H)[1]
			except Exception:pass
	except Exception:pass
	return str(uuid.uuid5(uuid.NAMESPACE_DNS,socket.gethostname()))
def get_mac_address()->str:
	try:A=':'.join([f"{uuid.getnode()>>A&255:02x}"for A in range(0,12,2)][::-1]);return A
	except Exception:return _B
def generate_device_id()->dict:
	C='system_info'
	try:A=get_hardware_uuid();D=get_mac_address();B={'platform':platform.platform(),'machine':platform.machine(),'processor':platform.processor(),'system':platform.system(),'release':platform.release(),'node':platform.node(),'python_version':f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"};E=f"{A}_{json.dumps(B,sort_keys=_C)}";F=hashlib.sha256(E.encode()).hexdigest()[:32];return{_D:F,_E:A,_F:D,C:B}
	except Exception as G:H=str(uuid.uuid4()).replace('-','');return{_D:H,_E:_B,_F:_B,C:{'error':str(G)}}
def get_machine_identifier()->str:
	try:return str(uuid.uuid5(uuid.NAMESPACE_DNS,socket.gethostname()))
	except Exception:return str(uuid.uuid4())
def get_username_from_api(api_key:str)->tuple:
	A='Unknown'
	if not requests:return A,_B
	try:
		D={'Authorization':f"Bearer {api_key}"};E='https://vnstocks.com/api/vnstock/user/profile';B=requests.get(E,headers=D,timeout=10)
		if B.status_code==200:C=B.json();F=C.get('username',A);G=C.get(_I,_B);return F,G
	except Exception:pass
	return A,_B
def is_virtual_environment()->bool:return hasattr(sys,'real_prefix')or hasattr(sys,'base_prefix')and sys.base_prefix!=sys.prefix
def generate_user_info(python_executable:str,venv_path:str=_A,device_info:dict=_A,api_key:str=_A,verbose:bool=False)->dict:
	E=verbose;D=api_key;A=device_info
	if A is _A:A=generate_device_id()
	B='vnstock_cli_installer';C=_B
	if D:
		B,C=get_username_from_api(D)
		if E:print(f"[INFO] API: username={B}, email={C}")
	G={_J:f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",_K:python_executable,_L:is_virtual_environment(),_M:venv_path};F={'user':B,_I:C,'uuid':get_machine_identifier(),'os':platform.system(),_N:platform.version(),'ip':_B,'cwd':os.getcwd(),_G:G,'time':datetime.now().isoformat(),_D:A[_D],_E:A[_E],_F:A[_F]}
	if E:print(f"[INFO] Generated user_info keys: {list(F.keys())}")
	return F
def main():
	J='store_true';F='=';D=argparse.ArgumentParser(description='Generate VNStock user.json file (matches installer format)',formatter_class=argparse.RawDescriptionHelpFormatter,epilog='\nExamples:\n  # Generate user.json (will prompt for API key)\n  python3 generate_user_info.py\n  \n  # Generate with API key\n  python3 generate_user_info.py --api-key "your_api_key"\n  \n  # Generate with venv path\n  python3 generate_user_info.py --venv "/path/to/venv"\n  \n  # Verbose output\n  python3 generate_user_info.py --verbose\n  \n  # Display only (no save)\n  python3 generate_user_info.py --display-only\n        ');D.add_argument('--api-key',type=str,default=_A,help='API key for fetching user info from server');D.add_argument('--venv',type=str,default=_A,help='Path to virtual environment');D.add_argument('--verbose',action=J,help='Show verbose output');D.add_argument('--display-only',action=J,help='Display info without saving');D.add_argument('--output',type=str,default=_A,help='Custom output path for user.json');B=D.parse_args();E=B.venv or os.environ.get('VIRTUAL_ENV')
	if E:E=Path(E)
	C=B.output
	if not C:K=Path.home()/'.vnstock';C=K/'user.json'
	else:C=Path(C)
	if B.verbose:print(_H+F*70);print('VNStock User Info Generator');print(F*70)
	G=B.api_key
	if not G and not B.display_only:
		print('\nTo fetch accurate user info from VNStock API:');print('1. Get API key from: https://vnstocks.com/account');print('2. Paste it below (or press Enter to skip)\n');H=input('Enter your API key (optional): ').strip()
		if H:G=H
		else:print('(Skipping API fetch - will use local info only)')
	I=generate_device_id()
	if B.verbose:print(f"[INFO] Device ID: {I[_D]}")
	if G:
		if B.verbose:print(f"[INFO] Fetching user data from VNStock API...")
	if B.verbose:print(f"[INFO] Generating user information...")
	A=generate_user_info(python_executable=sys.executable,venv_path=str(E)if E else _A,device_info=I,api_key=G,verbose=B.verbose);print(_H+F*70);print('📋 User Information Generated');print(F*70);print(f"\nUser: {A["user"]}");print(f"Email: {A[_I]}");print(f"UUID: {A["uuid"]}");print(f"Device ID: {A[_D]}");print(f"Hardware UUID: {A[_E]}");print(f"MAC Address: {A[_F]}");print(f"\nOS: {A["os"]}");print(f"OS Version: {A[_N]}");print(f"CWD: {A["cwd"]}");print(f"\nPython Information:");print(f"   Version: {A[_G][_J]}");print(f"   Executable: {A[_G][_K]}");print(f"   Virtual Env: {A[_G][_M]or"Not set"}");print(f"   Is Virtual: {A[_G][_L]}");print(f"\nTime: {A["time"]}");print(F*70)
	if not B.display_only:
		C.parent.mkdir(parents=_C,exist_ok=_C)
		with open(C,'w')as L:json.dump(A,L,indent=2)
		C.chmod(384);print(f"\n✅ Saved to: {C}")
	else:print(f"\n⚠️  Display-only mode: File not saved");print(f"   To save, run without --display-only flag")
	print()
if __name__=='__main__':main()