import argparse
import sys
import json
from pathlib import Path
from marco.core import repository
from marco.cli.interactive import build_interactive_config
from marco.cli import web_serve

def main():
    parser = argparse.ArgumentParser(prog="marco", description="Marco Dataset Versioning System")
    subparsers = parser.add_subparsers(dest="command", required=True)
    
    p_init = subparsers.add_parser("init", help="Initialize a marco repository")
    p_init.add_argument("path", nargs="?", default=".", help="Path to initialize")
    
    p_upload = subparsers.add_parser("upload", help="Create a dataset version")
    p_upload.add_argument("file", help="Path to raw dataset string/CSV/TSV")
    p_upload.add_argument("-c", "--config", help="Path to config.json")
    p_upload.add_argument("-t", "--tag", help="Tag for the version")
    p_upload.add_argument("-u", "--user", default="unknown", help="User name")
    
    subparsers.add_parser("list", help="List all dataset versions")
    
    p_diff = subparsers.add_parser("diff", help="Compare two dataset versions")
    p_diff.add_argument("v1", help="Version Hash or Tag 1")
    p_diff.add_argument("v2", help="Version Hash or Tag 2")
    p_diff.add_argument("-o", "--out", default="reports", help="Output directory for the markdown report")
    
    p_restore = subparsers.add_parser("restore", aliases=["checkout"], help="Restore processed data to your workspace")
    p_restore.add_argument("version", help="Version Hash or Tag")
    p_restore.add_argument("-o", "--out", default="data.tsv", help="Where to save the processed file")
    
    p_export = subparsers.add_parser("export", help="Export a version to tar.gz")
    p_export.add_argument("version", help="Version Hash or Tag")
    p_export.add_argument("dest", help="Destination folder")
    
    p_import = subparsers.add_parser("import", help="Import a version from tar.gz")
    p_import.add_argument("tarball", help="Path to exported tar.gz")

    subparsers.add_parser("generate-web", help="Serve the Marco React UI")
    
    args = parser.parse_args()
    repo_path = Path.cwd()
    
    if args.command == "init":
        p = args.path if args.path else "."
        repository.init_repo(p)
        print(f"Initialized Marco repository in {Path(p).resolve() / '.marco'}")
        
    elif args.command == "upload":
        raw_path = Path(args.file)
        if not raw_path.exists():
            print(f"Error: File {raw_path} does not exist.")
            sys.exit(1)
            
        if args.config:
            config = json.loads(Path(args.config).read_text(encoding='utf-8'))
        else:
            config = build_interactive_config()
            
        tags = [args.tag] if args.tag else []
        vid = repository.create_version(raw_path, config, repo_path, user=args.user, tags=tags)
        print(f"Successfully processed and generated version: {vid}")
        
    elif args.command == "list":
        try:
            versions = repository.list_versions(repo_path)
            print(f"{'Version':<10} | {'Created At':<20} | {'User':<10} | {'Tags':<20}")
            print("-" * 68)
            for v in versions:
                short = v['version_id'][:8]
                d = v.get('created_at', '')[:19].replace('T', ' ')
                u = v.get('created_by', 'unknown')
                t = ", ".join(v.get('tags', []))
                print(f"{short:<10} | {d:<20} | {u:<10} | {t:<20}")
        except Exception as e:
            print(f"Failed to list versions: {e}")
            
    elif args.command == "diff":
        from marco.core.comparator import compare_versions, generate_markdown_report
        
        try:
            report_data = compare_versions(args.v1, args.v2, repo_path)
            out_path = generate_markdown_report(report_data, Path(args.out))
            print(f"✅ Successfully compared {args.v1} vs {args.v2}")
            print(f"📄 Markdown Report generated at: {out_path.resolve()}")
        except Exception as e:
            print(f"Failed to compare versions: {e}")
            
    elif args.command in ["restore", "checkout"]:
        try:
            dest = repository.restore_version(args.version, args.out, repo_path)
            print(f"✅ Successfully restored dataset to: {dest.resolve()}")
        except Exception as e:
            print(f"Failed to restore dataset: {e}")
            
    elif args.command == "export":
        tar_path = repository.export_version(args.version, args.dest, repo_path)
        print(f"Exported to {tar_path}")
        
    elif args.command == "import":
        vid = repository.import_version(args.tarball, repo_path)
        print(f"Successfully imported version {vid}")

    elif args.command == "generate-web":
        web_serve.serve()

if __name__ == "__main__":
    main()
