import os
import sys
from .client import JulesPlanner
from .github import get_issue_context, post_comment_to_github

def main():
    """Main execution function."""
    print("🚀 Jules Planning Integration Started")

    # Get API key
    api_key = os.getenv("JULES_API_KEY")
    if not api_key:
        error_msg = """❌ **Jules Planning Error**

The `JULES_API_KEY` secret is not configured.

To enable Jules planning:
1. Go to [Jules Settings](https://jules.google.com/settings#api)
2. Create a new API key
3. Go to repository Settings → Secrets and variables → Actions
4. Add a new secret named `JULES_API_KEY`
5. Set the value to your Jules API key

For more information, see the [Jules API documentation](https://developers.google.com/jules/api).
"""
        print(error_msg)
        try:
            post_comment_to_github(error_msg)
        except Exception:
            pass # Use best effort if git token is also missing or other issues
        sys.exit(1)

    # Get repository info
    repo = os.getenv("GITHUB_REPOSITORY")
    if not repo or "/" not in repo:
        error_msg = "❌ Error: Could not determine repository owner and name"
        print(error_msg)
        try:
            post_comment_to_github(error_msg)
        except Exception:
            pass
        sys.exit(1)

    repo_owner, repo_name = repo.split("/", 1)

    try:
        # Get issue/PR context
        print("📋 Extracting issue context...")
        context = get_issue_context()
        print(f"   Issue #{context['number']}: {context['title']}")
        print(f"   Requested by: @{context['author']}")

        # Generate plan
        print("🤔 Generating architecture plan with Jules...")
        planner = JulesPlanner(api_key, repo_owner, repo_name)
        plan = planner.generate_plan(context)

        # Format the response
        formatted_response = f"""## 📐 Jules Architecture Plan

*Generated architecture and design plan for this request*

---

{plan}

---

<sub>🤖 Generated by Jules AI | Requested by @{context['author']}</sub>
"""

        # Post to GitHub
        print("📤 Posting plan to GitHub...")
        post_comment_to_github(formatted_response)

        print("✅ Jules planning completed successfully")

    except Exception as e:
        error_msg = f"""❌ **Jules Planning Error**

An error occurred while generating the plan:

```
{str(e)}
```

Please check the workflow logs for more details.
"""
        print(f"Error: {str(e)}")
        post_comment_to_github(error_msg)
        sys.exit(1)

if __name__ == "__main__":
    main()
