#!/usr/bin/env python3
"""Script to check status of all drafts."""

from __future__ import annotations

import sys
from pathlib import Path

# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from replymarketing.core.api_client import ApiClient
from replymarketing.core.auth_manager import AuthManager
from replymarketing.core.draft_manager import DraftManager
from replymarketing.utils.config import ensure_config_dir


def format_status_badge(status: str) -> str:
    """Format status with emoji/color indicator."""
    status_map = {
        "draft": "📝",
        "pending": "⏳",
        "approved": "✅",
        "rejected": "❌",
        "published": "🚀",
        "unknown": "❓",
    }
    return f"{status_map.get(status.lower(), '❓')} {status.upper()}"


def format_date(date_str: str | None) -> str:
    """Format date string for display."""
    if not date_str:
        return "—"
    # Simple formatting - could be enhanced with proper date parsing
    return date_str[:10] if len(date_str) > 10 else date_str


def display_drafts_table(drafts: list) -> None:
    """Display drafts in a formatted table."""
    if not drafts:
        print("\n📭 No drafts found for this agent.")
        return

    # Header
    print("\n" + "═" * 90)
    print(f"📋 DRAFT STATUS OVERVIEW - {len(drafts)} draft(s) found")
    print("═" * 90)
    print()

    # Status summary
    status_counts = {}
    for draft in drafts:
        status = draft.status.lower()
        status_counts[status] = status_counts.get(status, 0) + 1

    print("📊 Summary by Status:")
    for status, count in sorted(status_counts.items()):
        badge = format_status_badge(status)
        print(f"   {badge}: {count}")
    print()
    print("─" * 90)

    # Draft details
    print(f"\n{'ID':<24} {'STATUS':<12} {'SUBMITTED':<12} {'REVIEWED':<12} {'FEEDBACK'}")
    print("─" * 90)

    for draft in drafts:
        status = format_status_badge(draft.status).replace("📝 ", "").replace("⏳ ", "").replace("✅ ", "").replace("❌ ", "").replace("🚀 ", "").replace("❓ ", "")
        submitted = format_date(draft.submitted_at)
        reviewed = format_date(draft.reviewed_at)
        feedback = (draft.feedback[:30] + "...") if draft.feedback and len(draft.feedback) > 30 else (draft.feedback or "—")
        
        print(f"{draft.draft_id:<24} {status:<12} {submitted:<12} {reviewed:<12} {feedback}")

    print("─" * 90)

    # Next steps based on status
    pending = [d for d in drafts if d.status.lower() == "pending"]
    rejected = [d for d in drafts if d.status.lower() == "rejected"]
    draft_status = [d for d in drafts if d.status.lower() == "draft"]

    print("\n📌 Next Steps:")
    if pending:
        print(f"   • {len(pending)} draft(s) pending approval - awaiting review")
    if rejected:
        print(f"   • {len(rejected)} draft(s) rejected - needs revision based on feedback")
    if draft_status:
        print(f"   • {len(draft_status)} draft(s) in draft status - ready to submit for approval")
    if not any([pending, rejected, draft_status]):
        print("   • All drafts processed - no action needed")

    print()
    print("═" * 90)


def main() -> int:
    """Main entry point."""
    ensure_config_dir()

    # Initialize auth manager to get credentials
    auth_manager = AuthManager()
    auth_manager.reload_from_disk()

    api_key = auth_manager.get_api_key()
    agent_id = auth_manager.get_agent_id()

    if not api_key or not agent_id:
        print("❌ Error: Not authenticated. Please run the CLI and complete setup first.")
        return 1

    # Initialize API client and draft manager
    api_client = ApiClient(api_key)
    draft_manager = DraftManager(api_client, agent_id)

    # Fetch all drafts
    print("🔄 Fetching draft statuses...")
    drafts = draft_manager.list_drafts()

    # Display results
    display_drafts_table(drafts)

    # Show management URL
    base_url = "https://reply-marketingz.vercel.app"
    print(f"\n🔗 Manage all drafts:")
    print(f"   {base_url}/approval/drafts/{agent_id}")
    print()

    api_client.close()
    return 0


if __name__ == "__main__":
    sys.exit(main())
