from jira import JIRA
from .config import JiraConfig
import requests


class JiraService:
    def __init__(self, config: JiraConfig):
        self.config = config
        try:
            self.client = JIRA(
                server=config.server_url,
                basic_auth=(config.email, config.token),
                options={
                    'verify': True,
                    'headers': {
                        'Accept': 'application/json'
                    }
                }
            )
            
            # Test the connection by making a simple API call
            self.client.server_info()
            
        except requests.exceptions.ConnectionError as e:
            raise ValueError(f"Could not connect to Jira server at {config.server_url}. Please check the URL and your internet connection.")
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 401:
                raise ValueError("Authentication failed. Please check your email and API token.")
            elif e.response.status_code == 403:
                raise ValueError("Permission denied. Please check your email and API token have the correct permissions.")
            else:
                raise ValueError(f"HTTP Error {e.response.status_code}: {e.response.text}")
        except Exception as e:
            raise ValueError(f"Failed to initialize Jira client: {str(e)}")
    
    def get_issue_description(self, issue_key: str) -> str:
        """
        Get the description of a Jira issue.
        
        Args:
            issue_key: The Jira issue key (e.g., 'PROJECT-123')
            
        Returns:
            str: The description of the issue
            
        Raises:
            ValueError: If there's an error accessing the issue
        """
        try:
            issue = self.client.issue(issue_key)
            return issue.fields.description or ""
        except Exception as e:
            raise ValueError(f"Could not get issue {issue_key}: {str(e)}")
    
    def update_issue(self, issue_key: str, fields: dict) -> None:
        """
        Update a Jira issue with the provided fields.
        
        Args:
            issue_key: The Jira issue key (e.g., 'PROJECT-123')
            fields: Dictionary of fields to update
            
        Raises:
            ValueError: If there's an error updating the issue
        """
        try:
            issue = self.client.issue(issue_key)
            issue.update(fields=fields)
        except Exception as e:
            raise ValueError(f"Could not update issue {issue_key}: {str(e)}")
    
    def add_comment(self, issue_key: str, comment: str) -> None:
        """
        Add a comment to a Jira issue.
        
        Args:
            issue_key: The Jira issue key (e.g., 'PROJECT-123')
            comment: The comment text to add
            
        Raises:
            ValueError: If there's an error adding the comment
        """
        try:
            self.client.add_comment(issue_key, comment)
        except Exception as e:
            raise ValueError(f"Could not add comment to issue {issue_key}: {str(e)}")
    
    @classmethod
    def from_env(cls):
        """
        Create a JiraService instance using environment variables for configuration.
        """
        config = JiraConfig.from_env()
        return cls(config) 