import argparse
import sys
import os
from . import render_to_file, RenderOptions

def main():
    parser = argparse.ArgumentParser(description="CoreImR 1.2.0 - The Ultimate Zero-Dependency Converter")
    parser.add_argument("source", help="URL, local HTML, PHP, or Markdown file to render.")
    parser.add_argument("-o", "--output", required=True, help="Output file path (e.g. result.png, invoice.pdf). Format is inferred.")
    
    # Appearance
    parser.add_argument("--width", type=int, default=1200, help="Viewport width in pixels")
    parser.add_argument("--height", type=int, default=None, help="Viewport height in pixels")
    parser.add_argument("--scale", type=float, default=2.0, help="Device scale factor (Retina 2.0+)")
    parser.add_argument("--transparent", action="store_true", help="Transparent background")
    parser.add_argument("--dark-mode", action="store_true", help="Enforce Dark Mode theme")
    parser.add_argument("--full-page", action="store_true", help="Auto-crop to full scroll length")
    
    # Processing
    parser.add_argument("--delay", type=int, default=0, help="Wait milliseconds before capture (JS load)")
    parser.add_argument("--quality", type=int, default=90, help="JPEG/WEBP compression quality (1-100)")
    
    # Scraping Hacks
    parser.add_argument("--user-agent", help="Spoof browser device")
    parser.add_argument("--disable-js", action="store_true", help="Prevent Javascript Execution")
    parser.add_argument("--disable-web-security", action="store_true", help="Drop CORS restrictions")
    parser.add_argument("--ignore-ssl-errors", action="store_true", help="Bypass bad HTTPS certificates")
    
    args = parser.parse_args()

    # Determine input type
    url = None
    file_path = None
    markdown = None
    
    source = args.source
    if source.startswith('http://') or source.startswith('https://'):
        url = source
    elif os.path.exists(source):
        file_path = source
    else:
        # Treat as raw Markdown string natively if not file/url
        markdown = source

    options = RenderOptions(
        width=args.width,
        height=args.height,
        scale=args.scale,
        delay=args.delay,
        transparent=args.transparent,
        allow_net=not args.disable_web_security,
        user_agent=args.user_agent,
        disable_js=args.disable_js,
        dark_mode=args.dark_mode,
        full_page=args.full_page,
        ignore_ssl_errors=args.ignore_ssl_errors
    )

    try:
        render_to_file(
            path=args.output,
            url=url,
            file_path=file_path,
            markdown=markdown if not file_path else None, 
            options=options,
            quality=args.quality
        )
        print(f"✅ CoreImR successfully rendered: {args.output}")
    except Exception as e:
        print(f"❌ CoreImR Error: {str(e)}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    main()
