"""Test Flow config fallback functionality."""

import os
import pytest
from pathlib import Path
from unittest.mock import patch, mock_open
import yaml

from mithril.client import FCPClient
from mithril.errors import ConfigError


class TestFlowConfigFallback:
    """Test reading Flow SDK config as fallback."""
    
    def test_reads_flow_config_when_env_missing(self, monkeypatch, tmp_path):
        """Test client reads ~/.flow/config.yaml when env vars missing."""
        # Clear env vars
        monkeypatch.delenv("FCP_API_KEY", raising=False)
        monkeypatch.delenv("FCP_PROJECT", raising=False)
        
        # Create mock config
        config = {
            "api_key": "flow-test-key",
            "project": "flow-test-project"
        }
        config_content = yaml.dump(config)
        
        # Mock home directory and config file
        with patch('pathlib.Path.home', return_value=tmp_path):
            config_path = tmp_path / ".flow" / "config.yaml"
            config_path.parent.mkdir(parents=True)
            config_path.write_text(config_content)
            
            # Create client - should read from config
            client = FCPClient()
            assert client.api_key == "flow-test-key"
            assert client.project_id == "flow-test-project"
    
    def test_env_vars_take_precedence(self, monkeypatch, tmp_path):
        """Test environment variables override Flow config."""
        # Set env vars
        monkeypatch.setenv("FCP_API_KEY", "env-key")
        monkeypatch.setenv("FCP_PROJECT", "env-project")
        
        # Create mock config with different values
        config = {
            "api_key": "flow-key",
            "project": "flow-project"
        }
        config_content = yaml.dump(config)
        
        with patch('pathlib.Path.home', return_value=tmp_path):
            config_path = tmp_path / ".flow" / "config.yaml"
            config_path.parent.mkdir(parents=True)
            config_path.write_text(config_content)
            
            # Create client - should use env vars
            client = FCPClient()
            assert client.api_key == "env-key"
            assert client.project_id == "env-project"
    
    def test_partial_env_uses_config(self, monkeypatch, tmp_path):
        """Test partial env vars are supplemented by config."""
        # Only set API key in env
        monkeypatch.setenv("FCP_API_KEY", "env-key")
        monkeypatch.delenv("FCP_PROJECT", raising=False)
        
        # Config has project
        config = {
            "api_key": "flow-key",
            "project": "flow-project"
        }
        config_content = yaml.dump(config)
        
        with patch('pathlib.Path.home', return_value=tmp_path):
            config_path = tmp_path / ".flow" / "config.yaml"
            config_path.parent.mkdir(parents=True)
            config_path.write_text(config_content)
            
            # Should use env key but config project
            client = FCPClient()
            assert client.api_key == "env-key"
            assert client.project_id == "flow-project"
    
    def test_missing_config_file_is_ignored(self, monkeypatch):
        """Test missing config file doesn't break when env vars exist."""
        monkeypatch.setenv("FCP_API_KEY", "test-key")
        monkeypatch.setenv("FCP_PROJECT", "test-project")
        
        with patch('pathlib.Path.exists', return_value=False):
            # Should work fine with env vars
            client = FCPClient()
            assert client.api_key == "test-key"
            assert client.project_id == "test-project"
    
    def test_invalid_yaml_is_ignored(self, monkeypatch, tmp_path):
        """Test invalid YAML doesn't crash, falls back to env."""
        monkeypatch.setenv("FCP_API_KEY", "test-key")
        monkeypatch.setenv("FCP_PROJECT", "test-project")
        
        with patch('pathlib.Path.home', return_value=tmp_path):
            config_path = tmp_path / ".flow" / "config.yaml"
            config_path.parent.mkdir(parents=True)
            config_path.write_text("invalid: yaml: content: {")
            
            # Should work with env vars despite bad config
            client = FCPClient()
            assert client.api_key == "test-key"
            assert client.project_id == "test-project"
    
    def test_error_message_mentions_flow_init(self, monkeypatch):
        """Test error message guides users to flow init."""
        monkeypatch.delenv("FCP_API_KEY", raising=False)
        monkeypatch.delenv("FCP_PROJECT", raising=False)
        
        with patch('pathlib.Path.exists', return_value=False):
            with pytest.raises(ConfigError, match="flow init"):
                FCPClient()