"""Configuration management for bakalari-cli."""

import json
import os
from pathlib import Path
from dataclasses import dataclass, field, asdict
from typing import Set


def get_config_dir() -> Path:
    """Get the configuration directory path."""
    # Use ~/.config/bakalari-cli on Linux/Mac, %APPDATA%/bakalari-cli on Windows
    if os.name == 'nt':
        base = Path(os.environ.get('APPDATA', Path.home()))
    else:
        base = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config'))
    
    config_dir = base / 'bakalari-cli'
    config_dir.mkdir(parents=True, exist_ok=True)
    return config_dir


def get_config_path() -> Path:
    """Get the configuration file path."""
    return get_config_dir() / 'config.json'


@dataclass
class Config:
    """Application configuration."""
    url: str = ""
    selected_groups: list[str] = field(default_factory=list)
    
    def save(self) -> None:
        """Save configuration to file."""
        config_path = get_config_path()
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(asdict(self), f, indent=2, ensure_ascii=False)
    
    @classmethod
    def load(cls) -> 'Config':
        """Load configuration from file."""
        config_path = get_config_path()
        
        if not config_path.exists():
            return cls()
        
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            return cls(
                url=data.get('url', ''),
                selected_groups=data.get('selected_groups', []),
            )
        except (json.JSONDecodeError, IOError):
            return cls()
    
    def clear(self) -> None:
        """Clear configuration."""
        self.url = ""
        self.selected_groups = []
        self.save()
    
    @property
    def has_url(self) -> bool:
        """Check if a URL is configured."""
        return bool(self.url and self.url.strip())


def extract_groups_from_timetable(timetable) -> list[str]:
    """Extract all unique group names from a timetable."""
    groups: Set[str] = set()
    
    for day in timetable.days:
        for lesson in day.lessons:
            if lesson.group and lesson.group.strip():
                groups.add(lesson.group.strip())
    
    return sorted(groups)


def filter_lessons_by_groups(lessons: list, selected_groups: list[str]) -> list:
    """Filter lessons to only include selected groups.
    
    If a lesson has no group, it's always included.
    If a lesson has a group, it's only included if that group is selected.
    """
    if not selected_groups:
        return lessons  # No filtering if no groups selected
    
    filtered = []
    for lesson in lessons:
        # Include if no group specified
        if not lesson.group or not lesson.group.strip():
            filtered.append(lesson)
        # Include if group matches
        elif lesson.group.strip() in selected_groups:
            filtered.append(lesson)
    
    return filtered
