# ankur_scraper/cli.py

import argparse
import sys
from ankur_scraper.dispatcher import run_scraper
from ankur_scraper.core.url_utils import normalize_url, validate_url_accessible
from ankur_scraper.logging_config import get_logger

info_logger = get_logger("info")
error_logger = get_logger("error")


def main():
    """Main entry point for the Ankur Scraper CLI."""
    parser = argparse.ArgumentParser(
        description="Ankur Scraper - Crawl and extract text content from websites.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  ankur_scraper --url example.com
  ankur_scraper --url www.example.com --depth 2
  ankur_scraper --url https://example.com --dynamic
  ankur_scraper --url example.com --depth 3 --timeout 15
        """
    )

    parser.add_argument(
        "--url",
        type=str,
        required=True,
        help="Website to scrape (e.g., example.com, www.example.com, or https://example.com)",
    )
    parser.add_argument(
        "--depth",
        type=int,
        default=1,
        help="Depth of link crawling within the domain (default: 1)",
    )
    parser.add_argument(
        "--dynamic",
        action="store_true",
        help="Enable dynamic scraping using headless browser for JS-rendered content",
    )
    parser.add_argument(
        "--timeout",
        type=int,
        default=10,
        help="Request timeout in seconds (default: 10)",
    )
    parser.add_argument(
        "--user-agent",
        type=str,
        default=None,
        help="Custom User-Agent string (optional)",
    )
    parser.add_argument(
        "--max-pages",
        type=int,
        default=200,
        help="Maximum number of pages to crawl (default: 200)",
    )
    parser.add_argument(
        "--skip-validation",
        action="store_true",
        help="Skip URL accessibility validation (faster but may fail later)",
    )

    args = parser.parse_args()

    # Normalize the URL
    try:
        normalized_url = normalize_url(args.url)
        info_logger.info(f"[bold cyan]Normalized URL:[/] {normalized_url}")
    except ValueError as e:
        error_logger.error(f"[bold red]Invalid URL:[/] {e}")
        sys.exit(1)
    
    # Validate URL is accessible (unless skipped)
    if not args.skip_validation:
        info_logger.info("Validating URL accessibility...")
        is_accessible, final_url = validate_url_accessible(normalized_url, timeout=args.timeout)
        
        if not is_accessible:
            error_logger.error(f"[bold red]URL is not accessible:[/] {normalized_url}")
            error_logger.error("Try with --skip-validation flag to bypass this check")
            sys.exit(1)
        
        if final_url != normalized_url:
            info_logger.info(f"[yellow]URL redirected to:[/] {final_url}")
            normalized_url = final_url

    # Run the scraper
    try:
        result = run_scraper(
            url=normalized_url,
            depth=args.depth,
            use_dynamic=args.dynamic,
            timeout=args.timeout,
            user_agent=args.user_agent,
            max_pages=args.max_pages
        )
        
        # Check if we got any data
        if result and result.get('data'):
            info_logger.info("\n[bold green]✅ Scraping completed successfully![/]")
            info_logger.info(f"Total sections extracted: {result['summary']['total_sections']}")
            info_logger.info(f"\n[cyan]💡 Tip:[/] Access the data in your code with result['data']")
        else:
            error_logger.warning("\n[yellow]⚠️  No data was extracted.[/]")
            error_logger.warning("Try with --dynamic flag or check if the URL requires login.")
            sys.exit(1)
        
    except KeyboardInterrupt:
        info_logger.info("\n[yellow]Scraping interrupted by user[/]")
        sys.exit(0)
    except Exception as e:
        error_logger.error(f"\n[bold red]Scraping failed:[/] {e}")
        import traceback
        error_logger.error(traceback.format_exc())
        sys.exit(1)


if __name__ == "__main__":
    main()