#!/usr/bin/env python3
"""
Command Line Interface for TMIN Package
"""

import argparse
import sys
import textwrap
import toml
from pathlib import Path
from .core import PIPE

def load_config_from_toml(file_path):
    """Load pipe configuration from TOML file"""
    try:
        with open(file_path, 'r') as f:
            config = toml.load(f)
        return config
    except Exception as e:
        print(f"Error loading TOML file: {e}")
        sys.exit(1)

def validate_required_args(args):
    """Check if we have all the important stuff we need"""
    required_fields = {
        'schedule': 'Pipe schedule (10, 40, 80, 120, 160)',
        'nps': 'Nominal pipe size (e.g., "2", "3/4")',
        'pressure': 'Design pressure (psi)',
        'pressure_class': 'Pressure class (150, 300, 600, 900, 1500, 2500)',
        'metallurgy': 'Metallurgy type',
        'allowable_stress': 'Allowable stress (psi)',
        'measured_thickness': 'Measured thickness (inches)'
    }
    
    missing_required = []
    for field, description in required_fields.items():
        if not hasattr(args, field) or getattr(args, field) is None:
            missing_required.append(f"{field} ({description})")
    
    if missing_required:
        print("Error: Missing required arguments:")
        for field in missing_required:
            print(f"  --{field}")
        print("\nUse --help for more information.")
        sys.exit(1)

def print_disclaimer():
    """Print the legal stuff we have to show"""
    disclaimer = ("\033[1mDISCLAIMER\033[0m\n\n"
        "TMIN is an engineering analysis tool intended to assist with pipe thickness "
        "evaluation and retirement planning in petrochemical, processing, and refinery "
        "environments. \033[1mIt is not a stand-alone indicator of piping integrity.\033[0m "
        "All results and recommendations generated by TMIN must be interpreted and "
        "applied by qualified professionals with appropriate engineering judgment and field "
        "inspection expertise.\n\n"
        "This software does \033[1mnot\033[0m account for all possible factors affecting piping "
        "integrity, and its analysis may be limited by assumptions, data quality, or unmodeled "
        "conditions. A detailed design document is provided with this package, outlining the "
        "scope, assumptions, and limitations of TMIN. \033[1mUsers are strongly encouraged "
        "to review this document before relying on the results.\033[0m\n\n"
        "By using TMIN, you acknowledge that:\n"
        "- The software is a decision-support tool, not a substitute for professional engineering assessment.\n"
        "- Final decisions regarding piping integrity and retirement must be made by qualified personnel, considering all relevant data and site-specific conditions.\n"
        "- The developers and distributors of TMIN accept no liability for any damages or losses resulting from the use or misuse of this software.\n"
    )
    print(textwrap.fill(disclaimer, width=80, replace_whitespace=False, subsequent_indent='    '))

def main():
    parser = argparse.ArgumentParser(
        description="TMIN - Pipe Thickness Analysis Tool",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Basic analysis with required arguments
  tmin -s 40 -n "2" -p 50 -c 150 -m "Intermediate/Low CS" -a 23333 -t 0.060

  # Analysis with corrosion rate and inspection year
  tmin -s 40 -n "2" -p 50 -c 150 -m "Intermediate/Low CS" -a 23333 -t 0.060 -r 10 -y 2023

  # Analysis with output directory
  tmin -s 40 -n "2" -p 50 -c 150 -m "Intermediate/Low CS" -a 23333 -t 0.060 -o ./reports

  # Analysis using TOML configuration file
  tmin -f pipe_config.toml -t 0.060

  # Show help
  tmin --help
        """
    )

    # TOML file option
    parser.add_argument(
        '-f', '--file',
        type=str,
        help='Load configuration from TOML file'
    )

    # Output directory
    parser.add_argument(
        '-o', '--output',
        type=str,
        default='Reports',
        help='Output directory for reports (default: Reports)'
    )

    # Required arguments
    parser.add_argument(
        '-s', '--schedule',
        type=str,
        choices=['10', '40', '80', '120', '160'],
        help='Pipe schedule'
    )
    parser.add_argument(
        '-n', '--nps',
        type=str,
        help='Nominal pipe size (e.g., "2", "3/4", "1-1/2")'
    )
    parser.add_argument(
        '-p', '--pressure',
        type=float,
        help='Design pressure (psi)'
    )
    parser.add_argument(
        '-c', '--pressure-class',
        type=int,
        choices=[150, 300, 600, 900, 1500, 2500],
        help='Pressure class'
    )
    parser.add_argument(
        '-m', '--metallurgy',
        type=str,
        choices=['Intermediate/Low CS', 'SS 316/316L', 'SS 304/304L', 'Inconel 625', 'Other'],
        help='Metallurgy type'
    )
    parser.add_argument(
        '-a', '--allowable-stress',
        type=float,
        help='Allowable stress (psi)'
    )
    parser.add_argument(
        '-t', '--measured-thickness',
        type=float,
        help='Measured thickness during inspection (inches)'
    )

    # Optional arguments
    parser.add_argument(
        '-d', '--design-temp',
        type=str,
        default='900',
        choices=['<900', '900', '950', '1000', '1050', '1100', '1150', '1200', '1250', '1250+'],
        help='Design temperature (default: 900)'
    )
    parser.add_argument(
        '--pipe-config',
        type=str,
        default='straight',
        choices=['straight', '90LR - Inner Elbow', '90LR - Outer Elbow'],
        help='Pipe configuration (default: straight)'
    )
    parser.add_argument(
        '-r', '--corrosion-rate',
        type=float,
        help='Corrosion rate (MPY)'
    )
    parser.add_argument(
        '--default-retirement-limit',
        type=float,
        help='Default retirement limit (inches)'
    )
    parser.add_argument(
        '--api-table',
        type=str,
        default='2025',
        choices=['2025', '2009'],
        help='API table version (default: 2025)'
    )
    parser.add_argument(
        '-y', '--year-inspected',
        type=int,
        help='Year when thickness was measured'
    )
    parser.add_argument(
        '--no-disclaimer',
        action='store_true',
        help='Skip disclaimer message'
    )

    args = parser.parse_args()

    # Print disclaimer unless skipped
    if not args.no_disclaimer:
        print_disclaimer()

    # Load configuration from TOML file if provided
    if args.file:
        config = load_config_from_toml(args.file)
        # Update args with TOML values (command line args take precedence)
        for key, value in config.items():
            if not hasattr(args, key) or getattr(args, key) is None:
                setattr(args, key, value)

    # Validate required arguments
    validate_required_args(args)

    # Set up output directory
    output_dir = Path(args.output)
    output_dir.mkdir(exist_ok=True)

    try:
        # Create pipe instance
        pipe = PIPE(
            schedule=args.schedule,
            nps=args.nps,
            pressure=args.pressure,
            pressure_class=args.pressure_class,
            metallurgy=args.metallurgy,
            allowable_stress=args.allowable_stress,
            design_temp=args.design_temp,
            pipe_config=args.pipe_config,
            corrosion_rate=args.corrosion_rate,
            default_retirement_limit=args.default_retirement_limit,
            API_table=args.api_table
        )

        # Generate full report
        print(f"\nGenerating analysis and reports in: {output_dir}")
        report_files = pipe.generate_full_report(
            measured_thickness=args.measured_thickness,
            year_inspected=args.year_inspected
        )

        print("\nAnalysis complete! Generated files:")
        for file_type, file_path in report_files.items():
            if file_type != "analysis_results":
                print(f"  {file_type}: {file_path}")

    except ValueError as e:
        print(f"Error: Invalid input - {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main() 