# Solving an equation with a function defined by an element of a list

I have the following piece of code:

    y[x_] := (x - 3)^2 + 2
x[a_] := Sort[Select[x /. NSolve[a == y[x], x], #  ∈ Reals && # > 0 &],Less][[1]]
x[2]

(* 3 *)

xx[a_] := Piecewise[{{x[a], a >= 2}}]
NSolve[xx[a] == 3, a]
(* Part::partw: Part 1 of {} does not exist. >>*)

(* {} *)


So if $a\geq2$ then x picks the smallest from the list of $2$ elements and xx is just x on the domain where x is defined. Now I want NSolve to return the value of $a$ for which xx[a]=3. Why does the above error show up? If I give the input xx[2] then I get the output 3 as required, but if I put xx[2] in NSolve it apparently evaluates xx[a] first (rather than immediately putting in numerical values for a), which yields the error. How can I fix this, so that NSolve returns the value 2?

I tried Reduce and FindRoot as well, which give the same error.

Note: this seems like a huge hassle for such an easy function, but I'm applying it to some more complicated functions which seemed irrelevant to mention here.

Edit: apparently the problem lies in the Select (and then Sort) part, since NSolve (and all other equation solvers) first puts in a variable a, then computes x[a] (so that selecting the positive reals does not make sense since a is not yet a number) and only then starts putting in the values of a... So the solution would be to create another equation solving function than the ones Mathematica has.

-