#!/usr/bin/env python3
# summary: Check fleet computers and show health notices.
"""starchaser fleet watch local | check | on | off | status

Read-only authenticated fleet checks, new alerts and a weekly summary in the notification bell.
"""
import contextlib
import importlib.machinery
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from pathlib import Path

STATE = Path(os.environ.get('XDG_STATE_HOME') or Path.home()/'.local/state') / 'starchaser/fleet-watch.json'


def read(path):
    try:
        value = json.loads(Path(path).read_text())
        return value if isinstance(value, dict) else {}
    except (ValueError, OSError):
        return {}


def attention(name, facts, now):
    alerts = []
    if isinstance(facts.get('diskTotal'), (int, float)) and facts['diskTotal'] > 0 and isinstance(facts.get('diskUsed'), (int, float)) and facts['diskUsed']/facts['diskTotal'] >= .9:
        alerts.append(name + ': drive almost full')
    backup = facts.get('backup') or {}
    if backup.get('configured') and (backup.get('error') or backup.get('last', 0) and now - backup['last'] >= 7*86400):
        alerts.append(name + (": backup didn't finish" if backup.get('error') else ': no backup in a week'))
    if facts.get('lastUpgrade', 0) > 0 and now - facts['lastUpgrade'] >= 21*86400:
        alerts.append(name + ": hasn't updated in 3 weeks")
    return alerts


def new_alerts(previous, current):
    return [alert for alert in current if alert not in previous]


def week_key(now):
    return datetime.fromtimestamp(now, timezone.utc).strftime('%G-W%V')


def local_health():
    home = Path.home()
    conf = read(home/'.config/starchaser/backup.json')
    backup = read(home/'.local/state/starchaser/backup.json')
    result = {'backup': {'configured': bool(conf.get('uuid')), 'last': backup.get('last', 0), 'error': str(backup.get('error') or '')[:200]}}
    disk = shutil.disk_usage(home)
    result.update(diskTotal=disk.total, diskUsed=disk.used)
    try:
        loader=importlib.machinery.SourceFileLoader('fleet_health_updates',str(Path(__file__).resolve().with_name('starchaser-updates')))
        spec=importlib.util.spec_from_loader(loader.name,loader);updates=importlib.util.module_from_spec(spec);loader.exec_module(updates)
        result['lastUpgrade']=updates.last_upgrade(updates.paclog_runs())
    except (OSError,ValueError,ImportError):
        pass
    return result


def load_link():
    loader=importlib.machinery.SourceFileLoader('fleet_watch_link',str(Path(__file__).resolve().with_name('starchaser-link')))
    spec=importlib.util.spec_from_loader(loader.name,loader);module=importlib.util.module_from_spec(spec);loader.exec_module(module);return module


def notify(L, title, words):
    credential=Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}')/'starchaser-notifications'/'token'
    try:
        with credential.open() as stream:
            result=subprocess.run(['starchaser', 'notify',f'--credential-fd={stream.fileno()}','-a','Starchaser','-i','network-workgroup',
                                   '-h','string:x-starchaser-settings:fleet',title,words],pass_fds=(stream.fileno(),),capture_output=True,timeout=10)
        return result.returncode == 0
    except (OSError,subprocess.SubprocessError):
        return False


def check():
    L=load_link(); F=L.fleet(); previous=read(STATE)
    if previous.get('enabled') is False:
        return previous
    doc=F.load()
    if doc.get('unreadable') or doc['local'].get('left'):
        raise ValueError("The fleet list couldn't be read. Nothing was contacted.")
    peers=[p for p in L.load_peers() if not p.get('role') and F.is_member(p['id'],p.get('key',''))]
    def probe(p):
        result=L.ssh_to(p,'health',timeout=20)
        try:
            value=json.loads(result.stdout) if result.returncode == 0 else {}
            if not isinstance(value,dict) or value.get('error'):return None
            return {'id':p['id'],'name':L.safe_name(p.get('name')),'facts':value}
        except (ValueError,TypeError):return None
    with ThreadPoolExecutor(max_workers=2) as pool:
        results=[r for r in pool.map(probe,peers) if r]
    facts=[{'id':L.device_id(),'name':'This computer','facts':local_health()},*results]
    now=time.time(); alerts=[a for row in facts for a in attention(row['name'],row['facts'],now)]
    old=previous.get('alerts',[]); fresh=new_alerts(old,alerts)
    if fresh and not notify(L,'Your fleet needs attention','\n'.join(fresh[:8])+'\nOpen Mission Control > Fleet to check.'):
        old=[a for a in old if a in alerts] # retry delivery on the next check
    else: old=alerts
    week=week_key(now); summary=previous.get('week','')
    if peers and summary != week and notify(L,'Your weekly fleet summary',f"{len(results)} of {len(peers)} other computers checked. {len(alerts)} items need attention. Open Mission Control > Fleet for details."):
        summary=week
    value={'enabled':True,'checked':int(now),'alerts':old,'week':summary,'computers':facts}
    F.write_atomic(STATE,json.dumps(value)+'\n',0o600)
    return value


def main(argv):
    if argv in ([],['--help'],['-h'],['help']):print(__doc__);return
    if argv==['local']:value=local_health()
    elif argv==['status']:value=read(STATE)
    elif argv in (['on'],['off']):
        L=load_link();value=read(STATE);value['enabled']=argv==['on'];L.fleet().write_atomic(STATE,json.dumps(value)+'\n',0o600)
    elif argv==['check']:value=check()
    else:raise ValueError('Choose local, check, on, off or status.')
    print(json.dumps(value))


if __name__=='__main__':
    try:main(sys.argv[1:])
    except (OSError,ValueError) as error:print(json.dumps({'ok':False,'error':str(error)}));sys.exit(1)
