import argparse
import sys

from tfcost.plan_parser import parse_plan
from tfcost.cost_calculator import calculate_cost
from tfcost.history import show_cost_trend
from importlib.metadata import version


def main():

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--summary",
        action="store_true",
        help="Show summary only"
    )

    parser.add_argument(
        "--fail-if-increase",
        type=float,
        help="Fail if cost increase exceeds this value"
    )

    parser.add_argument(
        "--output",
        choices=["table", "json"],
        default="table",
        help="Output format"
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"tfcost {version('tfcost')}",
    )

    parser.add_argument(
        "--trend",
        action="store_true",
        help="Show infrastructure cost trend"
    )

    parser.add_argument(
        "--var-file",
        help="Terraform variable file (e.g. prod.tfvars)"
    )

    parser.add_argument(
        "--compare",
        nargs=2,
        metavar=("ENV1", "ENV2"),
        help="Compare two Terraform variable files"
    )

    parser.add_argument(
        "--diff",
        action="store_true",
        help="Show cost difference between current and proposed infrastructure"
    )

    args = parser.parse_args()

    # --------------------------------
    # Cost trend
    # --------------------------------
    if args.trend:
        show_cost_trend()
        return

    # --------------------------------
    # Environment comparison
    # --------------------------------
    if args.compare:

        env1, env2 = args.compare

        print("\nRunning Terraform plan for:", env1)
        resources1, region1 = parse_plan(var_file=env1)
        cost1 = calculate_cost(resources1, region1, summary=True)

        print("\nRunning Terraform plan for:", env2)
        resources2, region2 = parse_plan(var_file=env2)
        cost2 = calculate_cost(resources2, region2, summary=True)

        diff = cost2 - cost1
        percent = (diff / cost1 * 100) if cost1 else 0

        print("\nTerraform Environment Cost Comparison")
        print("─────────────────────────────────────")
        print(f"{env1:20} ${cost1:>10.2f}")
        print(f"{env2:20} ${cost2:>10.2f}")
        print("")
        print(f"{'Difference':20} ${diff:>10.2f}")
        print(f"{'Change %':20} {percent:>10.2f} %")

        return

    # --------------------------------
    # Pull Request Cost Diff
    # --------------------------------
    if args.diff:

        print("\nCalculating current infrastructure cost...")
        resources_old, region_old = parse_plan()
        current_cost = calculate_cost(resources_old, region_old, summary=True)

        print("\nCalculating proposed infrastructure cost...")
        resources_new, region_new = parse_plan(var_file=args.var_file)
        new_cost = calculate_cost(resources_new, region_new, summary=True)

        diff = new_cost - current_cost
        percent = (diff / current_cost * 100) if current_cost else 0

        print("\nTerraform Cost Diff")
        print("────────────────────────────────")
        print(f"{'Current Infrastructure Cost':35} ${current_cost:>10.2f}")
        print(f"{'Proposed Infrastructure Cost':35} ${new_cost:>10.2f}")
        print("")
        print(f"{'Cost Increase':35} ${diff:>10.2f}")
        print(f"{'Change %':35} {percent:>10.2f}%")

        if diff > 0:
            print("\n⚠ Infrastructure cost will increase.")

        return

    # --------------------------------
    # Normal cost estimation
    # --------------------------------
    resources, region = parse_plan(var_file=args.var_file)

    cost_change = calculate_cost(
        resources,
        region,
        summary=args.summary,
        output=args.output
    )

    # --------------------------------
    # Cost threshold guardrail
    # --------------------------------
    if args.fail_if_increase is not None:

        threshold = args.fail_if_increase

        print(f"\nThreshold : ${threshold:.2f}")

        if cost_change > threshold:
            print("Status    : FAIL")
            print("Cost increase exceeds allowed threshold.")
            sys.exit(1)
        else:
            print("Status    : PASS")