#!/usr/bin/env python3
from __future__ import annotations
import argparse,getpass,json,os,pathlib,shutil,subprocess,sys,tempfile,time,urllib.error,urllib.request
HOME=pathlib.Path.home(); BASE=HOME/'.visiqa'; CONFIG_PATH=BASE/'server-log-forwarder.json'; STATE_PATH=BASE/'server-log-forwarder-state.json'; LOG_PATH=BASE/'server-log-forwarder.log'; AGENT_PATH=BASE/'visiqa-log-forwarder.py'
MAX_BATCH_BYTES=5*1024*1024; MAX_BATCH_LINES=10000

def _load(path,default):
    try:return json.loads(path.read_text())
    except Exception:return default

def _save_private(path,data):
    path.parent.mkdir(parents=True,exist_ok=True); fd,tmp=tempfile.mkstemp(prefix=path.name+'.',dir=str(path.parent))
    try:
        with os.fdopen(fd,'w') as h: json.dump(data,h,indent=2,sort_keys=True); h.write('\n')
        os.chmod(tmp,0o600); os.replace(tmp,path)
    finally:
        try: os.unlink(tmp)
        except FileNotFoundError: pass

def _log(msg):
    BASE.mkdir(parents=True,exist_ok=True); stamp=time.strftime('%Y-%m-%d %H:%M:%S %z')
    with LOG_PATH.open('a') as h: h.write(f'{stamp} {msg}\n')
    try: os.chmod(LOG_PATH,0o600)
    except OSError: pass

def _request(url,token,data=None,timeout=30):
    headers={'X-Visiqa-Ingest-Token':token,'User-Agent':'VisiqaLogForwarder/1.0'}; method='POST' if data is not None else 'GET'
    if data is not None: headers['Content-Type']='text/plain; charset=utf-8'
    req=urllib.request.Request(url,data=data,headers=headers,method=method)
    try:
        with urllib.request.urlopen(req,timeout=timeout) as resp:
            body=resp.read().decode('utf-8',errors='replace'); return resp.status,json.loads(body) if body else {}
    except urllib.error.HTTPError as exc:
        body=exc.read().decode('utf-8',errors='replace')
        try: detail=json.loads(body).get('detail') or body
        except Exception: detail=body
        raise RuntimeError(f'Visiqa returned HTTP {exc.code}: {str(detail)[:300]}') from exc
    except urllib.error.URLError as exc: raise RuntimeError(f'Could not reach Visiqa: {exc.reason}') from exc

def _verify(cfg):
    status,payload=_request(cfg['endpoint'].rstrip('/')+'/verify',cfg['token'])
    if status!=200 or not payload.get('ok'): raise RuntimeError('Visiqa ingestion token verification failed')
    return payload

def _stat(path):
    try:
        st=path.stat(); return {'device':int(st.st_dev),'inode':int(st.st_ino),'size':int(st.st_size)}
    except FileNotFoundError:return None

def _read_new(path,previous):
    current=_stat(path)
    if not current:return b'',previous,'missing'
    offset=int((previous or {}).get('offset') or 0); same=previous and int(previous.get('device') or -1)==current['device'] and int(previous.get('inode') or -1)==current['inode']
    if not same or current['size']<offset: offset=0
    if current['size']==offset:return b'',{**current,'offset':offset},'unchanged'
    chunks=[]; total=0; lines=0; new_offset=offset
    with path.open('rb') as h:
        h.seek(offset)
        while lines<MAX_BATCH_LINES and total<MAX_BATCH_BYTES:
            line=h.readline()
            if not line: break
            if total and total+len(line)>MAX_BATCH_BYTES: break
            chunks.append(line); total+=len(line); lines+=1; new_offset=h.tell()
    return b''.join(chunks),{**current,'offset':new_offset},'read'

def _cron_line():
    py=shutil.which('python3') or sys.executable; return f'*/5 * * * * {py} {AGENT_PATH} run >> {LOG_PATH} 2>&1'

def _install_cron():
    line=_cron_line()
    try:
        p=subprocess.run(['crontab','-l'],capture_output=True,text=True,timeout=10); existing=p.stdout if p.returncode==0 else ''
        kept=[x for x in existing.splitlines() if 'visiqa-log-forwarder.py run' not in x]; kept.append(line); payload='\n'.join(kept).strip()+'\n'
        p2=subprocess.run(['crontab','-'],input=payload,text=True,capture_output=True,timeout=10); return p2.returncode==0,line
    except Exception:return False,line

def install(args):
    BASE.mkdir(parents=True,exist_ok=True)
    try: shutil.copy2(pathlib.Path(__file__).resolve(),AGENT_PATH)
    except shutil.SameFileError: pass
    os.chmod(AGENT_PATH,0o700); paths=[str(pathlib.Path(p).expanduser()) for p in args.log]; missing=[p for p in paths if not pathlib.Path(p).is_file()]
    if missing:
        print('Could not find these log files:'); [print('  -',p) for p in missing]; return 2
    token=getpass.getpass('Paste the Visiqa ingestion token (hidden): ').strip()
    if not token: print('No token entered.'); return 2
    cfg={'endpoint':args.endpoint.rstrip('/'),'token':token,'logs':paths,'website':args.website,'installed_at':int(time.time()),'agent_version':1}
    try: verified=_verify(cfg)
    except Exception as exc: print('Connection test failed:',exc); return 3
    state={'files':{},'last_success_at':None,'last_error':None}
    for raw in paths:
        p=pathlib.Path(raw); st=p.stat(); state['files'][raw]={'device':int(st.st_dev),'inode':int(st.st_ino),'size':int(st.st_size),'offset':int(st.st_size)}
    _save_private(CONFIG_PATH,cfg); _save_private(STATE_PATH,state); cron_ok,cron_line=_install_cron()
    print('\nVisiqa connection verified ✓'); print('Website:',verified.get('website') or args.website); print('Source:',verified.get('source_name') or 'Server/CDN Logs'); print('Live logs:')
    for p in paths: print('  ✓',p)
    if cron_ok: print('Automatic forwarding: enabled every 5 minutes ✓')
    else:
        print('Automatic cron could not be installed automatically.'); print('In cPanel → Advanced → Cron Jobs, choose Every 5 Minutes and use this command:'); print(cron_line)
    print('\nHistorical log files are not resent by this installer. Upload .gz history separately in Visiqa.'); return 0

def run(_args):
    cfg=_load(CONFIG_PATH,None); state=_load(STATE_PATH,{'files':{},'last_success_at':None,'last_error':None})
    if not cfg:_log('ERROR forwarder is not installed'); return 2
    pending=[]; next_states={}
    for raw in cfg.get('logs') or []:
        data,nxt,_=_read_new(pathlib.Path(raw),(state.get('files') or {}).get(raw)); next_states[raw]=nxt
        if data: pending.append((raw,data))
    if not pending:
        state['files']={**(state.get('files') or {}),**{k:v for k,v in next_states.items() if v}}; state['last_error']=None; _save_private(STATE_PATH,state); return 0
    for raw,data in pending:
        try:
            status,payload=_request(cfg['endpoint'],cfg['token'],data=data)
            if status!=200: raise RuntimeError(f'Unexpected HTTP status {status}')
            state.setdefault('files',{})[raw]=next_states[raw]; state['last_success_at']=int(time.time()); state['last_error']=None; _save_private(STATE_PATH,state); _log(f"OK {pathlib.Path(raw).name} bytes={len(data)} accepted={payload.get('records_accepted')} rejected={payload.get('records_rejected')}")
        except Exception as exc:
            state['last_error']=str(exc)[:500]; _save_private(STATE_PATH,state); _log(f'ERROR {pathlib.Path(raw).name}: {exc}'); return 4
    return 0

def status(_args):
    cfg=_load(CONFIG_PATH,None); state=_load(STATE_PATH,{})
    if not cfg: print('Visiqa forwarder is not installed.'); return 2
    print('Visiqa Server Log Forwarder'); print('Website:',cfg.get('website') or ''); print('Endpoint:',cfg.get('endpoint') or ''); print('Token: stored privately (not displayed)'); print('Logs:')
    for raw in cfg.get('logs') or []:
        st=_stat(pathlib.Path(raw)); saved=(state.get('files') or {}).get(raw) or {}; print(f"  - {raw} | exists={'yes' if st else 'no'} | offset={saved.get('offset',0)}")
    if state.get('last_success_at'): print('Last successful push:',time.strftime('%Y-%m-%d %H:%M:%S %z',time.localtime(state['last_success_at'])))
    else: print('Last successful push: waiting for new log lines')
    if state.get('last_error'): print('Last error:',state['last_error'])
    try: verified=_verify(cfg); print('Visiqa connection: verified ✓',verified.get('source_name') or '')
    except Exception as exc: print('Visiqa connection: failed ✗',exc); return 3
    return 0

def set_token(_args):
    cfg=_load(CONFIG_PATH,None)
    if not cfg:
        print('Visiqa forwarder is not installed.'); return 2
    token=getpass.getpass('Paste the NEW Visiqa ingestion token (hidden): ').strip()
    if not token:
        print('No token entered.'); return 2
    test={**cfg,'token':token}
    try: verified=_verify(test)
    except Exception as exc:
        print('New token verification failed:',exc); return 3
    cfg['token']=token; _save_private(CONFIG_PATH,cfg)
    print('New ingestion token verified and saved ✓')
    print('Source:',verified.get('source_name') or '')
    print('Existing log offsets were preserved.'); return 0

def uninstall(_args):
    try:
        p=subprocess.run(['crontab','-l'],capture_output=True,text=True,timeout=10); existing=p.stdout if p.returncode==0 else ''; kept=[x for x in existing.splitlines() if 'visiqa-log-forwarder.py run' not in x]; subprocess.run(['crontab','-'],input=('\n'.join(kept).strip()+'\n') if kept else '',text=True,capture_output=True,timeout=10)
    except Exception: pass
    for path in (CONFIG_PATH,STATE_PATH):
        try:path.unlink()
        except FileNotFoundError:pass
    print('Visiqa automatic forwarding disabled. Local diagnostic log retained at',LOG_PATH); return 0

def main():
    p=argparse.ArgumentParser(description='Visiqa Server/CDN Log Forwarder'); sub=p.add_subparsers(dest='command',required=True); ins=sub.add_parser('install'); ins.add_argument('--endpoint',required=True); ins.add_argument('--website',required=True); ins.add_argument('--log',action='append',required=True); sub.add_parser('run'); sub.add_parser('status'); sub.add_parser('set-token'); sub.add_parser('uninstall'); args=p.parse_args(); return {'install':install,'run':run,'status':status,'set-token':set_token,'uninstall':uninstall}[args.command](args)
if __name__=='__main__': raise SystemExit(main())
