#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
import pytest
from unittest.mock import patch

from shared import MOCK_STATIC_PATHS

from sun.autostart import Autostart, main


def _make_autostart(tmp_path):
    info = {**MOCK_STATIC_PATHS, 'xdg_autostart': tmp_path}
    mock_configs = type('Configs', (), {'data_configs': info})()
    with patch('sun.autostart.configs_load', mock_configs):
        return Autostart()


class TestAutostart:

    def test_enable_from_disabled(self, tmp_path, capsys):
        (tmp_path / 'sun-daemon.desktop.sample').touch()
        _make_autostart(tmp_path).enable()
        assert (tmp_path / 'sun-daemon.desktop').exists()
        assert 'enabled' in capsys.readouterr().out

    def test_enable_already_enabled(self, tmp_path, capsys):
        (tmp_path / 'sun-daemon.desktop').touch()
        _make_autostart(tmp_path).enable()
        assert 'already enabled' in capsys.readouterr().out

    def test_enable_not_installed(self, tmp_path, capsys):
        _make_autostart(tmp_path).enable()
        assert 'not installed' in capsys.readouterr().out

    def test_disable_from_enabled(self, tmp_path, capsys):
        (tmp_path / 'sun-daemon.desktop').touch()
        _make_autostart(tmp_path).disable()
        assert (tmp_path / 'sun-daemon.desktop.sample').exists()
        assert 'disabled' in capsys.readouterr().out

    def test_disable_already_disabled(self, tmp_path, capsys):
        (tmp_path / 'sun-daemon.desktop.sample').touch()
        _make_autostart(tmp_path).disable()
        assert 'already disabled' in capsys.readouterr().out

    def test_disable_not_installed(self, tmp_path, capsys):
        _make_autostart(tmp_path).disable()
        assert 'not installed' in capsys.readouterr().out

    def test_status_enabled(self, tmp_path, capsys):
        (tmp_path / 'sun-daemon.desktop').touch()
        _make_autostart(tmp_path).status()
        assert 'enabled' in capsys.readouterr().out

    def test_status_disabled(self, tmp_path, capsys):
        (tmp_path / 'sun-daemon.desktop.sample').touch()
        _make_autostart(tmp_path).status()
        assert 'disabled' in capsys.readouterr().out

    def test_status_not_installed(self, tmp_path, capsys):
        _make_autostart(tmp_path).status()
        assert 'not installed' in capsys.readouterr().out

    def test_invalid_action_exits(self, tmp_path, monkeypatch, capsys):
        monkeypatch.setattr(sys, 'argv', ['sun-autostart', 'invalid'])
        with pytest.raises(SystemExit) as exc_info:
            _make_autostart(tmp_path).run()
        assert exc_info.value.code != 0
        assert 'invalid choice' in capsys.readouterr().err


class TestMain:

    def test_main_calls_run(self, monkeypatch):
        monkeypatch.setattr(sys, 'argv', ['sun-autostart', 'status'])
        with patch('sun.autostart.Autostart.status') as mock_status:
            main()
            mock_status.assert_called_once()
