"""
Submit command implementation.

This module implements the 'submit' command that builds and pushes
container images with OCI artifacts for training templates.

NEW ARCHITECTURE (podman-py + oras-py):
1. Build container image with podman-py
2. Push image to OCI registry
3. Attach hyperparameter definitions as ORAS referrers
"""

import argparse
import sys
from pathlib import Path

from ..config.manager import ConfigManager
from ..parser.extractor import ArgumentParserExtractor
from ..validator import PythonSyntaxValidator


def setup_submit_parser(subparsers: argparse._SubParsersAction) -> None:
    """
    Set up the submit command parser.

    Args:
        subparsers: Subparsers action from parent parser

    """
    parser = subparsers.add_parser(
        "submit",
        help="Build and push training container image",
        description="Build container image with podman and attach metadata with ORAS",
        epilog="""
Examples:
    # Build and push training image (after login)
    keynet-train submit train.py

    # Specify Dockerfile location
    keynet-train submit train.py --dockerfile ./Dockerfile

    # Add custom tags
    keynet-train submit train.py --tag latest --tag v1.0.0

Notes:
    - Requires 'keynet-train config login' first
    - Uses Harbor credentials from config
    - Requires podman installed and configured
    - Hyperparameters extracted automatically from argparse/click/typer
        """,
    )

    parser.add_argument(
        "entrypoint",
        type=str,
        help="Path to training script entrypoint (e.g., train.py)",
    )

    parser.add_argument(
        "--dockerfile",
        type=str,
        default="./Dockerfile",
        help="Path to Dockerfile (default: ./Dockerfile)",
    )

    parser.add_argument(
        "--tag",
        type=str,
        action="append",
        default=None,
        help="Image tags (can specify multiple times, default: latest)",
    )

    parser.add_argument(
        "--no-cache",
        action="store_true",
        help="Build without using cache",
    )

    parser.set_defaults(func=handle_submit)


def handle_submit(args: argparse.Namespace) -> int:
    """
    Handle submit command execution.

    NEW WORKFLOW:
    1. Validate entrypoint file exists and has valid Python syntax
    2. Extract argument metadata (argparse/click/typer)
    3. Build container image with podman-py
    4. Push image to OCI registry
    5. Attach hyperparameter JSON as ORAS referrer

    Args:
        args: Parsed command-line arguments containing:
            - entrypoint: Path to training script
            - dockerfile: Path to Dockerfile
            - tag: Image tags (list)
            - no_cache: Build without cache

    Returns:
        Exit code:
            - 0: Success
            - 1: Error

    """
    try:
        # Step 0: Load configuration and get credentials
        config_manager = ConfigManager()

        # Check for Harbor credentials
        harbor_creds = config_manager.get_harbor_credentials()
        if not harbor_creds:
            print("Error: No Harbor credentials configured", file=sys.stderr)
            print(
                "Please login first: keynet-train config login --server-url <url>",
                file=sys.stderr,
            )
            return 1

        # Check for API key
        api_key = config_manager.get_api_key()
        if not api_key:
            print("Warning: No API key found", file=sys.stderr)
            print("Some features may not work without authentication", file=sys.stderr)

        # Step 1: Validate entrypoint
        print("🔍 Validating entrypoint...")
        entrypoint = Path(args.entrypoint)

        if not entrypoint.exists():
            print(
                f"Error: Entrypoint file not found: {args.entrypoint}", file=sys.stderr
            )
            return 1

        if not entrypoint.is_file():
            print(
                f"Error: Entrypoint is not a file: {args.entrypoint}", file=sys.stderr
            )
            return 1

        # Validate Python syntax
        validator = PythonSyntaxValidator()
        success, error = validator.validate_file(entrypoint)

        if not success:
            print("Error: Python syntax validation failed:", file=sys.stderr)
            print(error, file=sys.stderr)
            return 1

        print(f"✓ Entrypoint validated: {entrypoint.name}")
        print()

        # Step 2: Extract argument metadata
        print("📝 Extracting argument metadata...")
        extractor = ArgumentParserExtractor()
        args_metadata = extractor.extract_metadata(str(entrypoint))

        if args_metadata.get("parser_type"):
            arg_count = len(args_metadata.get("arguments", []))
            print(
                f"✓ Detected {args_metadata['parser_type']} parser with {arg_count} arguments"
            )
            print()
        else:
            print("⚠ No argument parser detected")
            print()

        # Step 3: Build container image
        print("🐳 Building container image...")
        print(f"   Harbor registry: {harbor_creds['url']}")
        print(f"   Harbor username: {harbor_creds['username']}")
        print(f"   Dockerfile: {args.dockerfile}")
        tags = args.tag if args.tag else ["latest"]
        print(f"   Tags: {', '.join(tags)}")
        print()

        if api_key:
            print("✓ API key found")
        print("✓ Harbor credentials found")
        print()

        # TODO: Implement podman-py integration
        print("⚠️  NOT IMPLEMENTED: Container build with podman-py")
        print("    Next steps:")
        print("    1. Use podman-py to build image from Dockerfile")
        print("    2. Push image to OCI registry")
        print("    3. Use oras-py to attach hyperparameter JSON as referrer")
        print()

        # Placeholder for new implementation
        print("📦 Hyperparameter metadata that will be attached:")
        import json

        print(json.dumps(args_metadata, indent=2))
        print()

        print("✓ Submit workflow validated (implementation pending)")
        return 0

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        import traceback

        traceback.print_exc()
        return 1
