from __future__ import annotations

from pathlib import Path

import pygit2
from pygit2 import Config, Repository

from pygittools.tui.git_colors import (
	_colors_enabled,
	_load_color_specs,
	_load_palette,
	_token_to_rgb,
	init_tui_color_theme,
	log_entry_attrs,
	parse_git_color_spec,
)


def test_parse_git_color_spec_256_index() -> None:
	palette = _load_palette()
	parsed = parse_git_color_spec("36")
	assert parsed.foreground == palette[36]
	assert parsed.bold is False


def test_parse_git_color_spec_named_bold() -> None:
	parsed = parse_git_color_spec("cyan bold")
	assert parsed.foreground == (0, 170, 170)
	assert parsed.bold is True


def test_parse_git_color_spec_hex_and_background() -> None:
	parsed = parse_git_color_spec("#ff0000 #0000ff reverse")
	assert parsed.foreground == (255, 0, 0)
	assert parsed.background == (0, 0, 255)
	assert parsed.reverse is True


def test_token_to_rgb_bright_named() -> None:
	palette = _load_palette()
	rgb = _token_to_rgb("brightred", palette)
	assert rgb == (255, 0, 0)


def test_load_color_specs_from_repo_config(tmp_path: Path) -> None:
	# Isolated config file so global/system git colors cannot leak into defaults.
	config_path = tmp_path / "gitconfig"
	config_path.write_text("", encoding="utf-8")
	config = Config()
	config.add_file(str(config_path), pygit2.GIT_CONFIG_LEVEL_LOCAL)
	config["color.status.added"] = "33"
	config["color.status.changed"] = "38 bold"
	specs = _load_color_specs(config)
	assert specs["color.status.added"] == "33"
	assert specs["color.status.changed"] == "38 bold"
	assert specs["color.status.untracked"] == "red"


def test_colors_disabled_when_ui_false(committed_repo: Repository) -> None:
	committed_repo.config["color.ui"] = "false"
	assert _colors_enabled(committed_repo.config.snapshot()) is False


def test_init_theme_from_repo(committed_repo: Repository) -> None:
	committed_repo.config["color.status.added"] = "36"
	committed_repo.config["color.status.changed"] = "38"
	committed_repo.config["color.status.untracked"] = "7"
	theme = init_tui_color_theme(committed_repo)
	assert theme.staged != 0 or theme.enabled is False


def test_init_theme_without_repo() -> None:
	theme = init_tui_color_theme(None)
	assert theme.status_bar != 0


def test_section_header_defaults_differ_from_file_rows() -> None:
	theme = init_tui_color_theme(None)
	assert theme.section_header != theme.staged or theme.staged == 0


def test_log_entry_attrs_returns_three_values() -> None:
	init_tui_color_theme(None)
	hash_attr, date_attr, subject_attr = log_entry_attrs(focused=False, highlight=True)
	assert hash_attr != 0 or date_attr != 0 or subject_attr != 0