"""
DataShaper CLI - Command-line interface for data cleaning.
"""
import click
import sys
from pathlib import Path
from datashaper.engine.crashguard_engine import CrashGuardEngine
from datashaper.licensing.validator import LicenseValidator

@click.group()
@click.version_option(version="0.1.0")
def main():
    """DataShaper - Clean messy data 10× faster, no code required."""
    pass


@main.command()
@click.argument("input_file", type=click.Path(exists=True))
@click.option("--output", "-o", type=click.Path(), help="Output file path (default: input_cleaned.csv)")
@click.option("--license", "-l", help="License key (or set DATASHAPER_LICENSE env var)")
@click.option("--conservative", is_flag=True, help="Use conservative cleaning mode")
@click.option("--report", is_flag=True, help="Generate HTML quality report")
def clean(input_file, output, license, conservative, report):
    """Clean a CSV file and fix data quality issues."""
    
    # Validate license
    validator = LicenseValidator()
    license_info = validator.validate(license)
    
    if not license_info:
        click.echo("❌ Invalid or missing license key.", err=True)
        click.echo("💡 Get a free license at: https://datashaper.ai/pricing", err=True)
        sys.exit(1)
    
    tier = license_info.get("tier", "free")
    click.echo(f"🔑 License: {tier.upper()} tier")
    
    # Initialize engine
    engine = CrashGuardEngine(license_info=license_info)
    
    try:
        # Clean the file
        click.echo(f"🧹 Cleaning: {input_file}")
        result = engine.clean(
            file_path=input_file,
            conservative=conservative
        )
        
        # Determine output path
        if not output:
            input_path = Path(input_file)
            output = str(input_path.parent / f"{input_path.stem}_cleaned{input_path.suffix}")
        
        # Save cleaned data
        result.save(output)
        click.echo(f"✅ Cleaned data saved to: {output}")
        
        # Print summary
        click.echo(f"\n📊 Summary:")
        click.echo(f"  • Issues found: {result.issues_found}")
        click.echo(f"  • Fixes applied: {result.fixes_applied}")
        click.echo(f"  • Quality score: {result.quality_score:.1f}%")
        
        # Generate report if requested
        if report:
            if tier == "free":
                click.echo("⚠️  HTML reports require Pro tier or higher", err=True)
            else:
                report_path = str(Path(output).parent / f"{Path(output).stem}_report.html")
                result.generate_report(report_path)
                click.echo(f"📄 Report saved to: {report_path}")
        
    except Exception as e:
        click.echo(f"❌ Error: {str(e)}", err=True)
        sys.exit(1)


@main.command()
@click.argument("input_file", type=click.Path(exists=True))
@click.option("--output", "-o", type=click.Path(), default="bundle.zip", help="Output ZIP file")
@click.option("--license", "-l", help="License key")
def bundle(input_file, output, license):
    """Create a ZIP bundle with cleaned data, report, and schema."""
    
    # Validate license
    validator = LicenseValidator()
    license_info = validator.validate(license)
    
    tier = license_info.get("tier", "free") if license_info else "free"
    
    if tier == "free":
        click.echo("❌ ZIP bundle export requires Pro tier or higher.", err=True)
        click.echo("💡 Upgrade at: https://datashaper.ai/pricing", err=True)
        sys.exit(1)
    
    click.echo(f"📦 Creating bundle from: {input_file}")
    
    # Initialize engine
    engine = CrashGuardEngine(license_info=license_info)
    
    try:
        # Clean and bundle
        result = engine.clean(file_path=input_file)
        result.create_bundle(output)
        
        click.echo(f"✅ Bundle saved to: {output}")
        click.echo(f"   Contains: cleaned.csv, report.html, schema.json")
        
    except Exception as e:
        click.echo(f"❌ Error: {str(e)}", err=True)
        sys.exit(1)


@main.command()
@click.argument("license_key")
def activate(license_key):
    """Activate a license key on this machine."""
    
    from datashaper.licensing.hardware import HardwareFingerprint
    validator = LicenseValidator()
    hw = HardwareFingerprint()
    
    try:
        # Show machine ID
        machine_id = hw.get_machine_id()
        click.echo(f"🖥️  Machine ID: {machine_id[:16]}...")
        click.echo(f"🔑 Activating license: {license_key[:8]}...")
        
        # Validate online
        license_info = validator.activate(license_key)
        
        if license_info:
            tier = license_info.get("tier", "unknown")
            expiry = license_info.get("expiry")
            
            click.echo(f"✅ License activated successfully!")
            click.echo(f"   Tier: {tier.upper()}")
            if expiry:
                click.echo(f"   Expires: {expiry}")
            click.echo(f"   Saved to: ~/.datashaper/license.json")
        else:
            click.echo("❌ Invalid or already activated license key", err=True)
            click.echo("💡 Contact support if you believe this is an error", err=True)
            sys.exit(1)
            
    except Exception as e:
        error_msg = str(e)
        if "Cannot reach license server" in error_msg:
            click.echo("❌ Cannot reach license server. Check your internet connection.", err=True)
        else:
            click.echo(f"❌ Activation failed: {error_msg}", err=True)
        sys.exit(1)


@main.command()
def status():
    """Check license status and feature availability."""
    
    validator = LicenseValidator()
    license_info = validator.get_local_license()
    
    if not license_info:
        click.echo("❌ No license found")
        click.echo("💡 Get a free license at: https://datashaper.ai/pricing")
        sys.exit(1)
    
    tier = license_info.get("tier", "free")
    expiry = license_info.get("expiry")
    
    click.echo(f"✅ License active")
    click.echo(f"   Tier: {tier.upper()}")
    if expiry:
        click.echo(f"   Expires: {expiry}")
    
    # Show feature availability
    features = {
        "File size limit": "25 MB" if tier == "free" else ("1 GB" if tier == "pro" else "5 GB" if tier == "team" else "Unlimited"),
        "ZIP bundle export": "❌" if tier == "free" else "✅",
        "HTML reports": "❌" if tier == "free" else "✅",
        "CrashGuard": "Basic" if tier == "free" else ("Advanced" if tier in ["team", "enterprise"] else "Basic"),
    }
    
    click.echo("\n📋 Features:")
    for feature, value in features.items():
        click.echo(f"   • {feature}: {value}")


if __name__ == "__main__":
    main()
