#!/usr/bin/env python3
import time
import configparser
import os
from lib.statscollector import StatsCollector

def get_config():
    config = configparser.ConfigParser()
    config_home = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
    config_path = os.path.join(config_home, "stats-collector", "config.ini")

    if not os.path.exists(config_path):
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        config['DEFAULT'] = {
            'port': '5747',
            'interval': '60'
        }
        config['localhost'] = {
            'host': 'localhost',
            'displayname': 'Local System'
        }
        with open(config_path, 'w') as f:
            config.write(f)

    config.read(config_path)
    return config

def main():
    config = get_config()
    collector = StatsCollector()
    default_port = int(config['DEFAULT']['port'])
    interval = int(config['DEFAULT']['interval'])

    def collect_all():
        for section in config.sections():
            host = config[section]['host']
            port = int(config[section].get('port', default_port))
            collector.collect_from_host(host, port)

    if interval > 0:
        print(f"Starting continuous collection every {interval} seconds...")
        while True:
            collect_all()
            time.sleep(interval)
    else:
        collect_all()

if __name__ == '__main__':
    main()
